@blocklive/cli 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,1176 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runCli = exports.SIGNED_IN = exports.OPTION_NAMES = void 0;
4
+ const path_1 = require("path");
5
+ const util_1 = require("util");
6
+ const config_1 = require("./config");
7
+ const errors_1 = require("./errors");
8
+ const http_1 = require("./http");
9
+ const style_1 = require("./style");
10
+ const read_1 = require("./read");
11
+ const reads_1 = require("./reads");
12
+ const catalog_1 = require("./catalog");
13
+ const safe_1 = require("./safe");
14
+ const HELP = `Blocklive from the command line.
15
+
16
+ Usage: blocklive <command> [options]
17
+
18
+ Signing in
19
+ login Sign in through your browser (two-step verification needed);
20
+ --no-browser for a code to enter on another device
21
+ login --unattended
22
+ A sign-in that keeps working without you, for an AI agent or
23
+ a script on this computer: paste the setup code made on
24
+ blocklive.io (Developer, CLI sign-ins), then type the code
25
+ it prints on the Developer page and press Activate. It reads
26
+ the setup code from standard input only, and sends it only
27
+ to blocklive.io (a test code: only to a server on this
28
+ computer)
29
+ logout Sign out here and end the sign-in on Blocklive (one not yet
30
+ activated: cancel it)
31
+ whoami Who you are signed in as, what this sign-in may do, and for
32
+ an unattended one where it works from
33
+
34
+ Reading
35
+ events list The events you can see through this sign-in
36
+ event show <event> One event, by ID or slug: tickets sold, check-ins
37
+ guests list <event> Its guests (managers and admins)
38
+
39
+ promos list <event> Its promo codes, bulk codes and bulk imports (managers
40
+ and admins)
41
+
42
+ Changing (asks first; --yes to skip, --dry-run to only show the plan)
43
+ promos import <event> --file <codes.csv>
44
+ Import bulk codes as drafts (card checkout only):
45
+ --percent 100, --uses 1 or --unlimited, --per-guest 1,
46
+ --tickets "VIP;General" (default all). The sign-in
47
+ must allow "Edit drafts" (blocklive login)
48
+ promos undo <event> [<import>]
49
+ Your imports, or undo one of them
50
+
51
+ Events (nothing is public until it is published, on blocklive.io or with
52
+ event publish. Changes ask first, --yes to skip, --dry-run for the plan)
53
+ events create --team <team>
54
+ A new event, not published: --title, --starts and
55
+ --ends 2026-12-01T19:00+01:00 (default: the next hour,
56
+ an hour long), --time-zone (default this computer's).
57
+ The sign-in must allow "Edit drafts" (managers and
58
+ admins; 10 a team a day)
59
+ events edit <event> Change its draft: --title, --subtitle, --description
60
+ or --description-file <file>, --starts, --ends,
61
+ --time-zone (keeps the clock times), --location <text
62
+ or link>, --hide-location or --show-location. Or
63
+ --cover <file>, on its own: its cover image (a
64
+ still PNG, JPEG or WebP, at most 4 MB, with no
65
+ metadata; never an unattended sign-in). Or
66
+ --place <place ID>, on its own: its place on the
67
+ map, by the ID places search shows (never an
68
+ unattended sign-in)
69
+ places search <text> Up to five places on Google Maps for the text, each
70
+ with the place ID events edit --place takes. The
71
+ sign-in must allow "Edit drafts"; 20 lookups a
72
+ person a day; never an unattended sign-in
73
+ event draft <event> Its draft beside what is live, and what isn't
74
+ published (managers and admins); --full for each
75
+ description whole
76
+ event publish <event> Publish it: the event, its tickets and prices go
77
+ live for everyone. Shows what goes live and asks
78
+ (--yes to skip), then waits for it to go through
79
+ (--no-wait to stop at once; --finish <publish> to
80
+ finish it later). The sign-in must allow "Publish"
81
+ (blocklive login; never an unattended one). An
82
+ event on its organiser's own wallet is published
83
+ on blocklive.io
84
+
85
+ Ticket types (drafts: live only once the event is published; asks first,
86
+ --yes to skip, --dry-run to only show the plan)
87
+ tickets list <event> Its ticket types: price, sold, sale window, on sale
88
+ or paused, shown or hidden, and what is live
89
+ (managers and admins)
90
+ tickets add <event> --title <title>
91
+ Add a ticket type, free unless --price 25 (in the
92
+ event's currency): --supply 100, --per-person 4,
93
+ --sale-starts/--sale-ends 2026-12-01T19:00:00+01:00,
94
+ --hidden, --paused, --show-sales, --not-transferable.
95
+ An event has at most 50 ticket types. The sign-in
96
+ must allow "Edit drafts"
97
+ tickets edit <event> <ticket>
98
+ Change one (its ID, from tickets list): the same
99
+ options, --price <amount> (0 makes it free),
100
+ --shown, --on-sale, --hide-sales, --transferable,
101
+ --order <n>. A price goes live with Publish. Or
102
+ --art <file>, on its own: its art (as --cover)
103
+ tickets remove <event> <ticket>
104
+ Remove one in its draft, with the promo codes and
105
+ token gates that unlock it. Not once any are sold
106
+ or in an open order. It stays on sale until the
107
+ event is published; putting it back is in the
108
+ event editor. Never an unattended sign-in
109
+
110
+ invoices list <event> Its orders' invoice status, why one waits, and the
111
+ seller of record (managers and admins; 25 a page)
112
+ invoice show <order> One order's invoice, billing details and documents
113
+
114
+ payment-account show <event>
115
+ Which account takes its payments, and whether a
116
+ switch would be refused now (also <team>)
117
+
118
+ Access (asked here, confirmed on blocklive.io with a new two-step code;
119
+ --no-wait to only ask, and see how it went with request show)
120
+ developers add <team> --email <address>
121
+ Add someone on the team as a developer, or invite
122
+ anyone else (admins and owners; --org for an
123
+ organization). Opens the page to confirm, then waits
124
+ payment-account choices <event>
125
+ The payout accounts an unpublished event could take:
126
+ its team's own, and Blocklive's (never an unattended
127
+ sign-in)
128
+ payment-account choose <event> --to <team|id>
129
+ Choose where its card payments are paid out, before
130
+ it is published (a team admin, an owner or admin of
131
+ its organization, or a Blocklive admin). The sign-in
132
+ must allow "Edit drafts"; never an unattended one;
133
+ the CLI takes no code. Opens the page to confirm,
134
+ then waits
135
+ payment-account switch <event> --to <account|team> --reason <why>
136
+ Move its card payments (Blocklive admins; also a
137
+ <team>); refused while it has card orders on its
138
+ account. Opens the page to confirm, then waits
139
+ invoice issue <order> Issue an order's invoice (managers and admins); it
140
+ isn't emailed. Opens the page to confirm, then waits
141
+ domains claim <event> <hostname>
142
+ Start connecting a custom domain to the event
143
+ (managers and admins). Opens the page to confirm,
144
+ then waits; domains list shows its DNS records
145
+
146
+ Your teams and organizations (by ID or slug)
147
+ developers list <team> Who manages API keys there, open invitations, and
148
+ whether developer access is on (admins and owners);
149
+ --org when an organization has the team's name
150
+ domains list <team> Its events' custom domains, their state and the DNS
151
+ records to set (managers and admins)
152
+
153
+ For scripts and agents
154
+ request show <request> Where a request you asked with --no-wait stands;
155
+ --wait to wait for the answer
156
+ commands Every command, its options, exit codes and
157
+ environment variables (--json for a program)
158
+ help This list
159
+
160
+ Options
161
+ --api <url> Which Blocklive to use, for login (default: https://blocklive.io;
162
+ or set BLOCKLIVE_API_URL). http://localhost:3000 for a local server.
163
+ --limit <n> How many rows (1 to 100)
164
+ --all Every page, not just the first
165
+ --org The name is an organization's
166
+ --profile <name> Use another saved sign-in (default: BLOCKLIVE_PROFILE, else
167
+ default)
168
+ --json Print JSON instead of text, and never ask
169
+ --no-browser login: sign in with a code (Enter still opens the page);
170
+ asking: only print the link to confirm
171
+ --no-wait Ask, print where to confirm it, and don't wait for the answer;
172
+ login --unattended: keep the sign-in and stop (it works once
173
+ activated); event publish: start it and stop
174
+ --unattended login: a sign-in that keeps working without you
175
+ --idempotency-key <uuid>
176
+ tickets add and edit, events create and edit, event
177
+ publish: the key to send
178
+ the change with, so sending it again never makes it twice
179
+ (default: a new one). A change whose answer is lost is sent
180
+ twice more with its key; then the CLI prints the key to run
181
+ it again with
182
+ --full event draft: each description whole
183
+ --finish <publish>
184
+ event publish: finish a publish already started (safe to
185
+ run again)
186
+ --help Show help
187
+ --version Show the version
188
+
189
+ An option a command doesn't take is refused (exit code 2). A limit that won't
190
+ clear in a minute is said at once, in Blocklive's words (exit code 5). An event
191
+ that is being published can't be changed from the CLI until it has finished.
192
+
193
+ BLOCKLIVE_NO_BROWSER=1 never opens a browser, whatever is pressed.
194
+
195
+ Anything that deletes, cancels, refunds or pays out is done on blocklive.io:
196
+ the CLI prints the link.`;
197
+ const OPTIONS = {
198
+ profile: { type: 'string' },
199
+ api: { type: 'string' },
200
+ 'base-url': { type: 'string' },
201
+ limit: { type: 'string' },
202
+ all: { type: 'boolean' },
203
+ org: { type: 'boolean' },
204
+ file: { type: 'string' },
205
+ percent: { type: 'string' },
206
+ uses: { type: 'string' },
207
+ unlimited: { type: 'boolean' },
208
+ 'per-guest': { type: 'string' },
209
+ tickets: { type: 'string' },
210
+ yes: { type: 'boolean' },
211
+ 'dry-run': { type: 'boolean' },
212
+ email: { type: 'string' },
213
+ to: { type: 'string' },
214
+ reason: { type: 'string' },
215
+ json: { type: 'boolean' },
216
+ 'insecure-storage': { type: 'boolean' },
217
+ 'no-browser': { type: 'boolean' },
218
+ 'no-wait': { type: 'boolean' },
219
+ unattended: { type: 'boolean' },
220
+ wait: { type: 'boolean' },
221
+ title: { type: 'string' },
222
+ description: { type: 'string' },
223
+ supply: { type: 'string' },
224
+ 'per-person': { type: 'string' },
225
+ 'sale-starts': { type: 'string' },
226
+ 'sale-ends': { type: 'string' },
227
+ hidden: { type: 'boolean' },
228
+ shown: { type: 'boolean' },
229
+ paused: { type: 'boolean' },
230
+ 'on-sale': { type: 'boolean' },
231
+ 'show-sales': { type: 'boolean' },
232
+ 'hide-sales': { type: 'boolean' },
233
+ transferable: { type: 'boolean' },
234
+ 'not-transferable': { type: 'boolean' },
235
+ order: { type: 'string' },
236
+ cover: { type: 'string' },
237
+ place: { type: 'string' },
238
+ art: { type: 'string' },
239
+ price: { type: 'string' },
240
+ currency: { type: 'string' },
241
+ 'idempotency-key': { type: 'string' },
242
+ team: { type: 'string' },
243
+ starts: { type: 'string' },
244
+ ends: { type: 'string' },
245
+ 'time-zone': { type: 'string' },
246
+ subtitle: { type: 'string' },
247
+ 'description-file': { type: 'string' },
248
+ location: { type: 'string' },
249
+ 'hide-location': { type: 'boolean' },
250
+ 'show-location': { type: 'boolean' },
251
+ full: { type: 'boolean' },
252
+ finish: { type: 'string' },
253
+ help: { type: 'boolean', short: 'h' },
254
+ version: { type: 'boolean' },
255
+ };
256
+ /** Every option parseArgs takes, for the catalog's test. */
257
+ exports.OPTION_NAMES = Object.keys(OPTIONS).map((name) => `--${name}`);
258
+ /** The commands that need a sign-in, by their catalog name. A command in
259
+ * the catalog without one here doesn't compile. */
260
+ exports.SIGNED_IN = {
261
+ 'events list': (read, rest) => listEvents(read, verb(rest, 'list', 0)),
262
+ 'event show': (read, rest) => showEvent(read, verb(rest, 'show', 1)[0]),
263
+ 'guests list': (read, rest) => listGuests(read, verb(rest, 'list', 1)[0]),
264
+ ...reads_1.READS,
265
+ };
266
+ // The modules only some commands need, loaded when they do: `--version`,
267
+ // `help`, `commands` and reads start without the login flow, the keychain
268
+ // tools or the lock.
269
+ const lazy = {
270
+ login: () => require('./login'),
271
+ secrets: () => require('./secrets'),
272
+ lock: () => require('./lock'),
273
+ unattended: () => require('./unattended'),
274
+ };
275
+ // What a setup code looks like, anywhere on a command line (unattended.ts).
276
+ const SETUP_CODE_LIKE = /bl_cls_/i;
277
+ // A variable that switches something on: set, and not 0 or false.
278
+ const on = (value) => !!value && !['0', 'false', 'no'].includes(value.toLowerCase());
279
+ // What every command prints goes through here: see safe.ts. With --json,
280
+ // stdout is escaped JSON, stderr is cleaned with no colour, and nothing is
281
+ // asked. With BLOCKLIVE_NO_BROWSER there is no browser at all, whatever is
282
+ // pressed. (--no-browser is narrower: login uses a code, and Enter still
283
+ // opens the /cli page; a command that asks only prints its link.)
284
+ function guard(io, json, noBrowser) {
285
+ const text = (line) => (0, safe_1.cleanLine)(line, style_1.STYLE_CODES);
286
+ return {
287
+ ...io,
288
+ out: (line) => io.out(json ? (0, safe_1.escapeJson)(line) : text(line)),
289
+ err: (line) => io.err(json ? (0, safe_1.cleanText)(line) : text(line)),
290
+ color: json ? false : io.color,
291
+ ask: json || !io.ask ? undefined : (q) => io.ask(text(q)),
292
+ browser: noBrowser ? undefined : io.browser,
293
+ };
294
+ }
295
+ async function runCli(argv, given) {
296
+ // Until the options are read, so that a wrong one is told as asked.
297
+ let json = argv.includes('--json');
298
+ let io = guard(given, json, true);
299
+ try {
300
+ // A setup code is read from standard input only: on a command line
301
+ // it stays in the shell's history and other programs can see it.
302
+ // Refused before anything else reads it, and never repeated.
303
+ if (argv.some((word) => SETUP_CODE_LIKE.test(word)))
304
+ throw (0, errors_1.usage)(lazy.unattended().CODE_ON_COMMAND_LINE);
305
+ const { values, positionals } = (0, util_1.parseArgs)({
306
+ args: argv,
307
+ options: OPTIONS,
308
+ allowPositionals: true,
309
+ strict: true,
310
+ });
311
+ json = !!values.json;
312
+ io = guard(given, json, on(given.env.BLOCKLIVE_NO_BROWSER));
313
+ if (values.version) {
314
+ io.out(json ? JSON.stringify({ version: http_1.VERSION }) : http_1.VERSION);
315
+ return errors_1.EXIT.ok;
316
+ }
317
+ const found = positionals.length ? (0, catalog_1.resolve)(positionals) : undefined;
318
+ if (positionals.length && !found)
319
+ throw (0, errors_1.usage)(`Unknown command \`${positionals[0]}\`. Run \`blocklive help\`.`);
320
+ const command = found?.command.name ?? 'help';
321
+ const rest = found?.rest ?? [];
322
+ // An option is a global one or its command's own (the catalog's):
323
+ // any other is refused, never quietly ignored.
324
+ const takes = new Set([
325
+ ...catalog_1.GLOBAL_OPTIONS.map((o) => o.name),
326
+ ...(catalog_1.COMMANDS.find((c) => c.name === command)?.options.map((o) => o.name) ?? []),
327
+ ]);
328
+ const stray = Object.keys(values).find((name) => !takes.has(`--${name}`));
329
+ if (stray !== undefined) {
330
+ const others = catalog_1.COMMANDS
331
+ .filter((c) => c.options.some((o) => o.name === `--${stray}`))
332
+ .map((c) => `\`${c.name}\``);
333
+ throw (0, errors_1.usage)(`\`blocklive ${command}\` doesn't take --${stray}${others.length
334
+ ? `: ${others.join(', ')} ${others.length === 1 ? 'does' : 'do'}`
335
+ : ''}. What each command takes: \`blocklive help\`, or \`blocklive commands --json\`.`);
336
+ }
337
+ if (values.help || command === 'help') {
338
+ io.out(json ? JSON.stringify((0, catalog_1.catalog)()) : HELP);
339
+ return errors_1.EXIT.ok;
340
+ }
341
+ if (['login', 'logout', 'whoami', 'commands'].includes(command) &&
342
+ rest.length > 0)
343
+ throw (0, errors_1.usage)(`\`${command}\` takes no arguments.`);
344
+ if (command === 'commands') {
345
+ listCommands(io, json);
346
+ return errors_1.EXIT.ok;
347
+ }
348
+ const profile = (0, config_1.profileName)(values.profile ?? (given.env.BLOCKLIVE_PROFILE || undefined));
349
+ const dir = io.configDir ?? (0, config_1.configDir)(io.env);
350
+ let config;
351
+ try {
352
+ config = (0, config_1.readConfig)(dir);
353
+ }
354
+ catch (error) {
355
+ // Signing in writes it again; anything else stops on it.
356
+ if (command !== 'login')
357
+ throw error;
358
+ config = (0, config_1.emptyConfig)();
359
+ }
360
+ let saved = Object.hasOwn(config.profiles, profile)
361
+ ? config.profiles[profile]
362
+ : undefined;
363
+ if (saved && typeof saved.baseUrl !== 'string')
364
+ throw new errors_1.CliError('Invalid API address in the saved CLI profile.');
365
+ if (saved)
366
+ saved = { ...saved, baseUrl: (0, config_1.baseUrl)(saved.baseUrl) };
367
+ const save = (next) => {
368
+ config = (0, config_1.updateProfile)(dir, profile, next && { ...next, credentialBinding: 'origin' }, command === 'login');
369
+ };
370
+ const store = (url) => lazy.secrets().chooseStore({
371
+ platform: io.platform,
372
+ dir,
373
+ url,
374
+ insecureStorage: !!values['insecure-storage'],
375
+ exec: io.exec,
376
+ profile,
377
+ });
378
+ const asked = values.api ?? values['base-url'] ?? io.env.BLOCKLIVE_API_URL;
379
+ // A profile CLI 0.4.0 or earlier saved holding a sign-in. Its saved
380
+ // address can't be trusted, so its pair (kept under the old fixed
381
+ // service name, secrets.ts legacyCredential) goes only to Blocklive
382
+ // itself, exactly PRODUCTION_URL, and only to end it: /logout (with
383
+ // /refresh if its access token must be renewed for that), or, for an
384
+ // unattended sign-in not yet activated, /login/unattended/cancel. A
385
+ // renewed pair is kept only where the old one was, and goes with it.
386
+ // Anywhere else nothing is sent: its copy and the profile are
387
+ // removed here, and the person ends it on that server's page.
388
+ // Throws, keeping everything, when Blocklive didn't end it.
389
+ const legacy = saved &&
390
+ saved.credentialBinding !== 'origin' &&
391
+ (saved.activating || saved.session)
392
+ ? saved
393
+ : undefined;
394
+ const endLegacy = async (old) => {
395
+ const kept = lazy.secrets().legacyCredential({
396
+ platform: io.platform,
397
+ dir,
398
+ exec: io.exec,
399
+ profile,
400
+ });
401
+ // Read only for Blocklive itself: anywhere else it isn't needed.
402
+ const found = old.baseUrl === config_1.PRODUCTION_URL ? kept.find() : undefined;
403
+ if (!found) {
404
+ kept.remove();
405
+ save();
406
+ return 'local';
407
+ }
408
+ const { store: where, pair } = found;
409
+ if (old.activating && !old.session) {
410
+ const done = await lazy.unattended().cancelSetup((0, http_1.createClient)({
411
+ baseUrl: config_1.PRODUCTION_URL,
412
+ auth: {
413
+ access: () => pair.access,
414
+ renew: async () => false,
415
+ },
416
+ fetchImpl: io.fetch,
417
+ wait: io.wait,
418
+ raw: json,
419
+ }), {
420
+ wait: io.wait,
421
+ site: new URL(config_1.PRODUCTION_URL).host,
422
+ until: old.activating.until,
423
+ });
424
+ if (done !== 'activated') {
425
+ kept.remove();
426
+ save();
427
+ return done;
428
+ }
429
+ // Activated meanwhile: ended below, as any other. Never
430
+ // asked about first (/whoami): only ending it is sent.
431
+ }
432
+ await endSignIn((0, http_1.createClient)({
433
+ baseUrl: config_1.PRODUCTION_URL,
434
+ auth: renewing(where, profile, config_1.PRODUCTION_URL, pair, io, true),
435
+ fetchImpl: io.fetch,
436
+ wait: io.wait,
437
+ raw: json,
438
+ }), old.session ?? { unattended: true }, config_1.PRODUCTION_URL, io);
439
+ kept.remove();
440
+ save();
441
+ return 'ended';
442
+ };
443
+ // Whether the person activated an unattended sign-in set up here:
444
+ // waiting for it (login) or one look (any other command). Active, it
445
+ // is this profile's sign-in from now on, as whoami describes it;
446
+ // cancelled or expired, its pair and the profile go.
447
+ const activated = async (url, tokens, pair, { until, once }) => {
448
+ const asking = (0, http_1.createClient)({
449
+ baseUrl: url,
450
+ auth: { access: () => pair.access, renew: async () => false },
451
+ fetchImpl: io.fetch,
452
+ wait: io.wait,
453
+ raw: json,
454
+ });
455
+ let state;
456
+ try {
457
+ state = await lazy
458
+ .unattended()
459
+ .activation(asking, { until, wait: io.wait, once });
460
+ }
461
+ catch (error) {
462
+ if (error instanceof errors_1.CliError &&
463
+ error.exitCode === errors_1.EXIT.refused) {
464
+ tokens.remove(profile);
465
+ save();
466
+ }
467
+ throw error;
468
+ }
469
+ if (state === 'pending')
470
+ return undefined;
471
+ const me = await (0, http_1.createClient)({
472
+ baseUrl: url,
473
+ auth: renewing(tokens, profile, url, pair, io),
474
+ fetchImpl: io.fetch,
475
+ wait: io.wait,
476
+ raw: json,
477
+ }).get('/whoami');
478
+ save({ baseUrl: url, session: me });
479
+ return me;
480
+ };
481
+ if (command !== 'login' && values.unattended)
482
+ throw (0, errors_1.usage)('--unattended goes with `blocklive login`.');
483
+ if (command === 'login' && values['no-wait'] && !values.unattended)
484
+ throw (0, errors_1.usage)('--no-wait goes with `blocklive login --unattended`, or a command that asks.');
485
+ if (command === 'login' && values.unattended) {
486
+ const u = lazy.unattended();
487
+ if (values['no-browser'])
488
+ throw (0, errors_1.usage)('--no-browser is for a sign-in you approve in a browser: an unattended one is activated on the Developer page.');
489
+ // Only Blocklive itself, whatever --api, BLOCKLIVE_API_URL or the
490
+ // profile says: until it is activated, the code is the sign-in.
491
+ // A live code goes only to https://blocklive.io, a test one only
492
+ // to this computer: checked again once the code is read.
493
+ const url = (0, config_1.baseUrl)(asked ?? saved?.baseUrl);
494
+ if (!u.unattendedHost(url))
495
+ throw u.notUnattendedHost(url, values.api !== undefined || values['base-url'] !== undefined
496
+ ? 'option'
497
+ : io.env.BLOCKLIVE_API_URL
498
+ ? 'environment'
499
+ : 'profile');
500
+ // Never over a sign-in this profile still holds.
501
+ if (u.holdsSignIn(saved))
502
+ throw (0, errors_1.usage)(u.profileInUse(profile, saved));
503
+ const style = (0, style_1.styler)(io.color);
504
+ const site = new URL(url).host;
505
+ // Before the code is spent: no keychain, or one that can't keep
506
+ // it (a throwaway value written and removed), stops it here.
507
+ const tokens = store(url);
508
+ lazy.secrets().probeStore(tokens);
509
+ io.err('');
510
+ for (const line of u.introduction(style, site))
511
+ io.err(line);
512
+ io.err('');
513
+ if (!io.readSecret)
514
+ throw (0, errors_1.usage)('There is no standard input here to read the setup code from.');
515
+ const code = u.checkedSetupCode(await io.readSecret(' Setup code (hidden as you paste it): '), url);
516
+ const api = (0, http_1.createClient)({
517
+ baseUrl: url,
518
+ fetchImpl: io.fetch,
519
+ wait: io.wait,
520
+ raw: json,
521
+ });
522
+ const made = await u.redeem(api, code);
523
+ // Kept as every sign-in is, before anything else can fail.
524
+ tokens.write(profile, lazy.secrets().joinTokens(made.tokens));
525
+ if (tokens.kind === 'file')
526
+ io.err(style.dim('Kept in a file only you can read (--insecure-storage): anything running as you on this computer can use it from here until it ends.'));
527
+ save({ baseUrl: url, activating: { until: made.until } });
528
+ io.err('');
529
+ for (const line of u.nextSteps(style, site, made.until, made.check))
530
+ io.err(line);
531
+ io.err('');
532
+ if (values['no-wait']) {
533
+ if (json)
534
+ io.out(JSON.stringify({
535
+ signedIn: false,
536
+ unattended: true,
537
+ activateBefore: made.until,
538
+ checkCode: made.check,
539
+ }));
540
+ else
541
+ io.out("Not waiting: it isn't active until you type the code on the Developer page and press Activate. Then `blocklive whoami` shows it.");
542
+ return errors_1.EXIT.ok;
543
+ }
544
+ io.err(` ${style.purple('◆')} Waiting for you to activate it on the page… ${style.dim('Ctrl-C to stop waiting')}`);
545
+ // As `blocklive login` does: the code goes on the page, and
546
+ // anything typed here while it waits gets that said.
547
+ const enter = io.browser?.enter?.();
548
+ lazy.login().typedHere(enter, io.err, style, 'the Developer page in your browser');
549
+ let me;
550
+ try {
551
+ me = await activated(url, tokens, made.tokens, {
552
+ until: made.until,
553
+ once: false,
554
+ });
555
+ }
556
+ finally {
557
+ enter?.stop();
558
+ }
559
+ if (json)
560
+ io.out(JSON.stringify({
561
+ signedIn: true,
562
+ unattended: true,
563
+ session: me,
564
+ }));
565
+ else
566
+ io.out(u.signedInWords(me, where(me), site));
567
+ return errors_1.EXIT.ok;
568
+ }
569
+ if (command === 'login') {
570
+ const { browserLogin, deviceLogin } = lazy.login();
571
+ const { joinTokens } = lazy.secrets();
572
+ const url = (0, config_1.baseUrl)(asked ?? saved?.baseUrl);
573
+ if (!familiar(url))
574
+ io.err(`Warning: ${url} is not Blocklive. Sign in there only if you run it yourself.`);
575
+ const tokens = store(url);
576
+ // Never over a sign-in an older CLI made here that Blocklive
577
+ // still honours: ended first, or said where to end it.
578
+ if (legacy) {
579
+ const was = await endLegacy(legacy);
580
+ io.err(was === 'local'
581
+ ? `Your earlier sign-in at ${legacy.baseUrl} may still be active: end it under CLI sign-ins at ${legacy.baseUrl}/developer.`
582
+ : `Ended your earlier sign-in on ${new URL(config_1.PRODUCTION_URL).host}.`);
583
+ }
584
+ const client = (0, http_1.createClient)({
585
+ baseUrl: url,
586
+ fetchImpl: io.fetch,
587
+ wait: io.wait,
588
+ raw: json,
589
+ });
590
+ // The steps go to stderr even with --json: the person needs them,
591
+ // and stdout stays the JSON answer.
592
+ const style = (0, style_1.styler)(io.color);
593
+ const here = browserHere(io);
594
+ const code = !!values['no-browser'] || !here.browser;
595
+ if (here.why && !values['no-browser'])
596
+ io.err(style.dim(here.why));
597
+ // The code flow still opens /cli on Enter when this computer has a
598
+ // browser (none with BLOCKLIVE_NO_BROWSER): the page, never the code.
599
+ const done = code
600
+ ? await deviceLogin({
601
+ baseUrl: url,
602
+ client,
603
+ browser: here.browser,
604
+ wait: io.wait,
605
+ say: io.err,
606
+ style,
607
+ })
608
+ : await browserLogin({
609
+ baseUrl: url,
610
+ client,
611
+ browser: here.browser,
612
+ wait: io.wait,
613
+ say: io.err,
614
+ style,
615
+ });
616
+ tokens.write(profile, joinTokens(done.tokens));
617
+ save({ baseUrl: url, session: done.session });
618
+ if (json)
619
+ io.out(JSON.stringify({ signedIn: true, session: done.session }));
620
+ else
621
+ io.out(`Signed in as ${done.session.person} ${where(done.session)}.`);
622
+ return errors_1.EXIT.ok;
623
+ }
624
+ if (saved && asked && (0, config_1.baseUrl)(asked) !== saved.baseUrl)
625
+ throw (0, errors_1.usage)(`This profile is signed in to ${saved.baseUrl}. Run \`blocklive login --api ${(0, config_1.baseUrl)(asked)}\`, or use another --profile.`);
626
+ if (legacy) {
627
+ if (command === 'logout') {
628
+ const was = await endLegacy(legacy);
629
+ if (was === 'local') {
630
+ const message = `End the old sign-in under CLI sign-ins at ${legacy.baseUrl}/developer, then run blocklive login for this profile.`;
631
+ if (json)
632
+ io.out(JSON.stringify({
633
+ signedOut: true,
634
+ endedOnBlocklive: false,
635
+ message,
636
+ }));
637
+ else
638
+ io.out(`Removed the local profile. ${message}`);
639
+ }
640
+ else if (json)
641
+ io.out(JSON.stringify({
642
+ signedOut: true,
643
+ endedOnBlocklive: true,
644
+ ...(was === 'cancelled' ? { cancelled: true } : {}),
645
+ }));
646
+ else
647
+ io.out(signedOutWords(was));
648
+ return errors_1.EXIT.ok;
649
+ }
650
+ throw new errors_1.CliError(`This profile was saved with an older CLI. ${legacy.baseUrl === config_1.PRODUCTION_URL
651
+ ? 'Run `blocklive logout`, then `blocklive login`.'
652
+ : `End the old sign-in under CLI sign-ins at ${legacy.baseUrl}/developer, then run \`blocklive logout\` and \`blocklive login\`.`}`, errors_1.EXIT.refused, 'not_signed_in');
653
+ }
654
+ // An unattended sign-in set up here, not yet activated: logout
655
+ // cancels it on Blocklive, any other command looks once.
656
+ if (saved?.activating && !saved.session) {
657
+ const tokens = store(saved.baseUrl);
658
+ const pair = lazy.secrets().splitTokens(tokens.read(profile));
659
+ const site = new URL(saved.baseUrl).host;
660
+ if (pair && command === 'logout') {
661
+ // Kept (and said why) when Blocklive can't be reached.
662
+ const done = await lazy.unattended().cancelSetup((0, http_1.createClient)({
663
+ baseUrl: saved.baseUrl,
664
+ auth: {
665
+ access: () => pair.access,
666
+ renew: async () => false,
667
+ },
668
+ fetchImpl: io.fetch,
669
+ wait: io.wait,
670
+ raw: json,
671
+ }), { wait: io.wait, site, until: saved.activating.until });
672
+ if (done !== 'activated') {
673
+ tokens.remove(profile);
674
+ save();
675
+ if (json)
676
+ io.out(JSON.stringify({
677
+ signedOut: true,
678
+ endedOnBlocklive: true,
679
+ ...(done === 'cancelled'
680
+ ? { cancelled: true }
681
+ : {}),
682
+ }));
683
+ else
684
+ io.out(signedOutWords(done));
685
+ return errors_1.EXIT.ok;
686
+ }
687
+ // Activated meanwhile: signed out below, as any other.
688
+ }
689
+ if (pair) {
690
+ const me = await activated(saved.baseUrl, tokens, pair, {
691
+ until: saved.activating.until,
692
+ once: true,
693
+ });
694
+ if (!me)
695
+ throw new errors_1.CliError(`This unattended sign-in isn't active yet. On the Developer page at ${site}, type the code \`blocklive login --unattended\` printed and press Activate, then run this again.`, errors_1.EXIT.refused, 'activation_pending');
696
+ }
697
+ saved = config.profiles[profile];
698
+ }
699
+ if (!saved?.session)
700
+ throw new errors_1.CliError('Not signed in. Run `blocklive login`.', errors_1.EXIT.refused, 'not_signed_in');
701
+ // What an unattended sign-in can't do, said before it is tried
702
+ // (Blocklive refuses it too): the catalog's attendedOnly.
703
+ const named = catalog_1.COMMANDS.find((c) => c.name === command);
704
+ if (saved.session.unattended && named?.attendedOnly)
705
+ throw new errors_1.CliError(`\`blocklive ${command}\` needs a sign-in you approve yourself, so an unattended sign-in can't run it. Ask the person to run it, signed in with \`blocklive login\`.`, errors_1.EXIT.refused, 'needs_attended_sign_in');
706
+ // Nor an option marked the same way (an image: --cover, --art; a
707
+ // place from the map: --place).
708
+ const attended = named?.options?.find((o) => o.attendedOnly &&
709
+ values[o.name.slice(2)] !==
710
+ undefined);
711
+ if (saved.session.unattended && attended)
712
+ throw new errors_1.CliError(`\`blocklive ${command} ${attended.name}\` needs a sign-in you approve yourself, so an unattended sign-in can't run it. Ask the person to run it, signed in with \`blocklive login\`.`, errors_1.EXIT.refused, 'needs_attended_sign_in');
713
+ // Nor, without the choice, guests' and buyers' details (the
714
+ // catalog's personalDetails).
715
+ if (saved.session.unattended &&
716
+ saved.session.personal === false &&
717
+ named?.personalDetails)
718
+ throw new errors_1.CliError(`\`blocklive ${command}\` reads guests’ or buyers’ details, and this unattended sign-in may not. Make one that may on the Developer page, or ask the person to run it, signed in with \`blocklive login\`.`, errors_1.EXIT.refused, 'personal_details_off');
719
+ const tokens = store(saved.baseUrl);
720
+ const token = lazy.secrets().splitTokens(tokens.read(profile));
721
+ if (!token)
722
+ throw new errors_1.CliError('Not signed in. Run `blocklive login`.', errors_1.EXIT.refused, 'not_signed_in');
723
+ const signedInTo = saved.baseUrl;
724
+ const client = (0, http_1.createClient)({
725
+ baseUrl: saved.baseUrl,
726
+ auth: renewing(tokens, profile, saved.baseUrl, token, io),
727
+ fetchImpl: io.fetch,
728
+ wait: io.wait,
729
+ onWait: (seconds) => io.err(`Rate-limited: waiting ${seconds} s…`),
730
+ raw: json,
731
+ });
732
+ if (command === 'logout') {
733
+ await endSignIn(client, saved.session, signedInTo, io);
734
+ tokens.remove(profile);
735
+ save();
736
+ if (json)
737
+ io.out(JSON.stringify({ signedOut: true, endedOnBlocklive: true }));
738
+ else
739
+ io.out(signedOutWords('ended'));
740
+ return errors_1.EXIT.ok;
741
+ }
742
+ if (command === 'whoami') {
743
+ const me = await client.get('/whoami');
744
+ if (json)
745
+ io.out(JSON.stringify({
746
+ ...me,
747
+ profile,
748
+ api: saved.baseUrl,
749
+ cliVersion: http_1.VERSION,
750
+ }));
751
+ else {
752
+ io.out(`${me.person} ${where(me)}`);
753
+ io.out(`May: ${me.actions.length
754
+ ? me.actions
755
+ .map((a) => catalog_1.ACTION_WORDS[a] ?? a)
756
+ .join('; ')
757
+ : 'read only'}`);
758
+ io.out(`Ends: ${me.endsAt}`);
759
+ if (me.unattended)
760
+ for (const line of lazy.unattended().unattendedWords(me))
761
+ io.out(line);
762
+ }
763
+ return errors_1.EXIT.ok;
764
+ }
765
+ const read = {
766
+ client,
767
+ // With --json, each Blocklive path comes with its address (url).
768
+ io: json
769
+ ? {
770
+ ...io,
771
+ out: (line) => io.out((0, read_1.linkedJson)(signedInTo, line)),
772
+ }
773
+ : io,
774
+ json,
775
+ base: saved.baseUrl,
776
+ profile,
777
+ values,
778
+ };
779
+ return await exports.SIGNED_IN[command](read, rest);
780
+ }
781
+ catch (error) {
782
+ const failure = error instanceof errors_1.CliError
783
+ ? error
784
+ : typeof error?.code === 'string' &&
785
+ error.code.startsWith('ERR_PARSE_ARGS')
786
+ ? (0, errors_1.usage)(error.message)
787
+ : new errors_1.CliError('Something went wrong. Run it again, or contact Blocklive.');
788
+ if (json)
789
+ io.out(JSON.stringify({
790
+ error: {
791
+ message: failure.message,
792
+ code: failure.code,
793
+ request_id: failure.requestId,
794
+ exit: failure.exitCode,
795
+ ...failure.details,
796
+ },
797
+ }));
798
+ else
799
+ io.err(failure.requestId
800
+ ? `${failure.message} (request ${failure.requestId})`
801
+ : failure.message);
802
+ return failure.exitCode;
803
+ }
804
+ }
805
+ exports.runCli = runCli;
806
+ // Ends a sign-in on Blocklive (`blocklive logout`), trying again through a
807
+ // dropped connection. Only once Blocklive has ended it (or said it had
808
+ // already ended: a 401) may it be forgotten here: forgetting a sign-in
809
+ // Blocklive still honours would leave no way to end it. Any other refusal
810
+ // keeps it, saying so: held_elsewhere (from another network) is still live
811
+ // where it was set up.
812
+ async function endSignIn(client, session, signedInTo, io) {
813
+ let ended = false;
814
+ for (let attempt = 1; !ended; attempt += 1) {
815
+ try {
816
+ await client.post('/logout', {});
817
+ ended = true;
818
+ }
819
+ catch (error) {
820
+ if ((0, errors_1.endedOnBlocklive)(error))
821
+ ended = true;
822
+ else if (error instanceof errors_1.CliError &&
823
+ error.code === 'held_elsewhere')
824
+ throw new errors_1.CliError(lazy
825
+ .unattended()
826
+ .heldElsewhereLogout(session, new URL(signedInTo).host), errors_1.EXIT.refused, 'held_elsewhere', error.requestId);
827
+ else if (error instanceof errors_1.CliError &&
828
+ error.exitCode === errors_1.EXIT.refused)
829
+ throw error;
830
+ else if (error instanceof errors_1.CliError &&
831
+ error.code === 'unreachable' &&
832
+ attempt < 3)
833
+ await io.wait(2000);
834
+ else
835
+ break;
836
+ }
837
+ }
838
+ // Every way it can still end.
839
+ if (!ended)
840
+ throw new errors_1.CliError(session.unattended
841
+ ? "Couldn't reach Blocklive to end this unattended sign-in, so it's still active. " +
842
+ 'Run `blocklive logout` again when you’re online, or end it under CLI sign-ins ' +
843
+ `at ${signedInTo}/developer. It also ends by itself after ${lazy
844
+ .unattended()
845
+ .idleWords(session.idleLimitMinutes)} unused.`
846
+ : "Couldn't reach Blocklive to end this sign-in, so it's still active. " +
847
+ 'Run `blocklive logout` again when you’re online, end it under CLI sign-ins ' +
848
+ `at ${signedInTo}/developer, or sign out of blocklive.io in the browser you ` +
849
+ `approved it from. It also ends by itself after ${idle(session.idleLimitMinutes)} unused.`, errors_1.EXIT.error, 'unreachable');
850
+ }
851
+ // What `blocklive logout` says once Blocklive ended it: an unattended
852
+ // sign-in not yet activated is cancelled, or was gone already.
853
+ function signedOutWords(done) {
854
+ return done === 'cancelled'
855
+ ? 'Cancelled on Blocklive: the unattended sign-in set up here was never activated, and now it can’t be. Forgotten here too.'
856
+ : done === 'gone'
857
+ ? 'Forgotten here. It was never activated, and Blocklive no longer has it: it had expired or was cancelled.'
858
+ : 'Signed out.';
859
+ }
860
+ // `blocklive commands`: the catalog, as a table or as JSON.
861
+ function listCommands(io, json) {
862
+ if (json) {
863
+ io.out(JSON.stringify((0, catalog_1.catalog)()));
864
+ return;
865
+ }
866
+ for (const line of (0, read_1.table)([
867
+ ['COMMAND', 'KIND', 'WHAT IT DOES'],
868
+ ...catalog_1.COMMANDS.map((c) => [c.name, c.kind, c.summary]),
869
+ ]))
870
+ io.out(line);
871
+ io.out('');
872
+ io.out('Kinds: read changes nothing; change asks first (--yes to skip); ask is confirmed on blocklive.io with two-step.');
873
+ io.out('Usage, options and exit codes: blocklive commands --json');
874
+ }
875
+ // This computer's browser: none over SSH (the browser would be on another
876
+ // computer, where the answer can't reach this one), nor on a Linux machine
877
+ // with no display. Then the code is the way, and why says so.
878
+ function browserHere(io) {
879
+ if (!io.browser)
880
+ return {};
881
+ if (io.env.SSH_CONNECTION || io.env.SSH_TTY)
882
+ return {
883
+ why: 'Signed in over SSH: sign in with a code from a browser on any device.',
884
+ };
885
+ if (io.platform === 'linux' && !io.env.DISPLAY && !io.env.WAYLAND_DISPLAY)
886
+ return {
887
+ why: 'No display here: sign in with a code from a browser on any device.',
888
+ };
889
+ return { browser: io.browser };
890
+ }
891
+ // How long a sign-in may sit unused, in words: 1 hour, or 8 for a door one.
892
+ function idle(minutes) {
893
+ const hours = Math.round((minutes ?? 60) / 60);
894
+ return hours === 1 ? '1 hour' : `${hours} hours`;
895
+ }
896
+ // Blocklive itself, or a server on this computer.
897
+ function familiar(url) {
898
+ const host = new URL(url).hostname;
899
+ return (host === 'blocklive.io' ||
900
+ host.endsWith('.blocklive.io') ||
901
+ ['localhost', '127.0.0.1', '[::1]'].includes(host));
902
+ }
903
+ function where(session) {
904
+ if (session.kind === 'developer' && session.key)
905
+ return `through the key “${session.key.name}”`;
906
+ const names = session.scopes.map((s) => s.name ?? `a ${s.kind}`);
907
+ return `at ${names.join(', ')}`;
908
+ }
909
+ // The access token lasts 15 minutes. When it is refused, the refresh token
910
+ // (used once) gets a new pair, kept at once: a refresh token used twice ends
911
+ // the sign-in. So renewing holds the profile's lock, and first takes a pair
912
+ // another command already renewed while it waited. On a computer nobody
913
+ // watches (an unattended sign-in) it must not lose the sign-in either:
914
+ // a refresh whose answer was lost (no answer, or Blocklive's own failure)
915
+ // is sent again once with the same token, which Blocklive answers with a
916
+ // new pair within 60 seconds from the same network (the retry rule);
917
+ // a new pair that can't be kept is tried again, and if it still can't be,
918
+ // the sign-in is ended on Blocklive rather than left live with nobody
919
+ // holding it, and the command says so;
920
+ // a refresh refused because this computer is somewhere the sign-in isn't
921
+ // held to keeps the pair (from where it was set up it still works), as
922
+ // does any refusal but a 401; one that ended says why (switched_off,
923
+ // sign_in_ended) and forgets it.
924
+ function renewing(tokens, profile, baseUrl, start, io,
925
+ // A legacy pair's lock: kept apart from the address's own sign-ins.
926
+ legacy = false) {
927
+ let current = start;
928
+ // Well inside the lock's 30 seconds, so another command never takes it
929
+ // over while this one still renews.
930
+ const dir = io.configDir ?? (0, config_1.configDir)(io.env);
931
+ const scope = legacy
932
+ ? lazy.secrets().LEGACY_SERVICE
933
+ : lazy.secrets().credentialScope(dir, baseUrl);
934
+ const plain = (0, http_1.createClient)({
935
+ baseUrl,
936
+ fetchImpl: io.fetch,
937
+ wait: io.wait,
938
+ maxWaits: 0,
939
+ timeoutMs: 12000,
940
+ });
941
+ return {
942
+ access: () => current.access,
943
+ renew: () => {
944
+ const { withLock } = lazy.lock();
945
+ return withLock((0, path_1.join)(dir, `${scope}.${profile}.renew.lock`), io.wait, renewOnce);
946
+ },
947
+ };
948
+ async function refresh(token) {
949
+ for (let attempt = 1;; attempt += 1) {
950
+ try {
951
+ return await plain.post('/refresh', { refresh_token: token });
952
+ }
953
+ catch (error) {
954
+ const lost = error instanceof errors_1.CliError &&
955
+ (error.code === 'unreachable' ||
956
+ error.code === 'unavailable');
957
+ if (!lost || attempt > 1)
958
+ throw error;
959
+ await io.wait(2000);
960
+ }
961
+ }
962
+ }
963
+ async function renewOnce() {
964
+ const { joinTokens, splitTokens } = lazy.secrets();
965
+ const stored = splitTokens(tokens.read(profile));
966
+ if (stored && stored.refresh !== current.refresh) {
967
+ current = stored;
968
+ return true;
969
+ }
970
+ let pair;
971
+ try {
972
+ pair = await refresh(current.refresh);
973
+ }
974
+ catch (error) {
975
+ if (error instanceof errors_1.CliError && error.exitCode === errors_1.EXIT.refused) {
976
+ // Still live (held_elsewhere: from where it was set up): kept.
977
+ if (!(0, errors_1.endedOnBlocklive)(error))
978
+ throw error;
979
+ tokens.remove(profile);
980
+ // Why an unattended one ended, for the agent to branch on.
981
+ if (error.code !== 'not_signed_in')
982
+ throw error;
983
+ return false;
984
+ }
985
+ throw error;
986
+ }
987
+ const next = splitTokens(`${pair.access_token}:${pair.refresh_token}`);
988
+ if (!next)
989
+ return false;
990
+ await keep(next, joinTokens(next));
991
+ current = next;
992
+ return true;
993
+ }
994
+ async function keep(next, value) {
995
+ for (let attempt = 1;; attempt += 1) {
996
+ try {
997
+ tokens.write(profile, value);
998
+ return;
999
+ }
1000
+ catch (error) {
1001
+ if (attempt < 3) {
1002
+ await io.wait(1000);
1003
+ continue;
1004
+ }
1005
+ }
1006
+ break;
1007
+ }
1008
+ // Nobody would hold a live sign-in: it ends now, on Blocklive. Only
1009
+ // its answer, or a 401, says it ended; any other refusal doesn't.
1010
+ let ended = false;
1011
+ try {
1012
+ await (0, http_1.createClient)({
1013
+ baseUrl,
1014
+ auth: { access: () => next.access, renew: async () => false },
1015
+ fetchImpl: io.fetch,
1016
+ wait: io.wait,
1017
+ maxWaits: 0,
1018
+ timeoutMs: 12000,
1019
+ }).post('/logout', {});
1020
+ ended = true;
1021
+ }
1022
+ catch (error) {
1023
+ ended = (0, errors_1.endedOnBlocklive)(error);
1024
+ }
1025
+ try {
1026
+ tokens.remove(profile);
1027
+ }
1028
+ catch {
1029
+ // The pair kept before is spent already.
1030
+ }
1031
+ const where = tokens.kind === 'keychain'
1032
+ ? 'the Keychain'
1033
+ : tokens.kind === 'secret-service'
1034
+ ? 'the Secret Service'
1035
+ : 'its file';
1036
+ throw new errors_1.CliError(ended
1037
+ ? `Couldn't save the renewed sign-in in ${where}, so it was ended on Blocklive rather than left running with nobody holding it. Fix ${where}, then sign in again.`
1038
+ : `Couldn't save the renewed sign-in in ${where}, nor end it on Blocklive: end it under CLI sign-ins at ${baseUrl}/developer.`, errors_1.EXIT.error, 'store_failed');
1039
+ }
1040
+ }
1041
+ // What `event show` shares with `event draft` and `event publish` (loaded
1042
+ // when it runs, as every command's file is).
1043
+ const events = () => require('./reads/events');
1044
+ // `events list`, `event show <event>`: the verb is optional, the event isn't.
1045
+ function verb(rest, expected, count) {
1046
+ const args = rest[0] === expected ? rest.slice(1) : rest;
1047
+ if (args.length !== count)
1048
+ throw (0, errors_1.usage)(count
1049
+ ? 'Name the event, by its ID or slug: e.g. `blocklive event show my-event`.'
1050
+ : 'This command takes no arguments.');
1051
+ if (count && !/^[A-Za-z0-9][A-Za-z0-9-]{0,199}$/.test(args[0]))
1052
+ throw (0, errors_1.usage)('An event is named by its ID or slug.');
1053
+ return args;
1054
+ }
1055
+ async function listEvents(read, _args) {
1056
+ const { rows, more } = await (0, read_1.pages)(read, '/events', (body) => body.events ?? []);
1057
+ if (read.json) {
1058
+ read.io.out(JSON.stringify({ events: rows, more }));
1059
+ return errors_1.EXIT.ok;
1060
+ }
1061
+ if (!rows.length) {
1062
+ read.io.out('No events here.');
1063
+ return errors_1.EXIT.ok;
1064
+ }
1065
+ for (const line of (0, read_1.table)([
1066
+ ['WHEN', 'EVENT', 'SLUG', 'TEAM', 'YOU'],
1067
+ ...rows.map((e) => [
1068
+ (0, read_1.whenSpan)(e.startsAt, e.endsAt, e.timeZone),
1069
+ e.title,
1070
+ e.slug,
1071
+ e.team?.name ?? '',
1072
+ e.role,
1073
+ ]),
1074
+ ]))
1075
+ read.io.out(line);
1076
+ if (more)
1077
+ read.io.out('More events: use --all, or --limit.');
1078
+ return errors_1.EXIT.ok;
1079
+ }
1080
+ async function showEvent(read, named) {
1081
+ const event = await read.client.get(`/events/${encodeURIComponent(named)}`);
1082
+ if (read.json) {
1083
+ read.io.out(JSON.stringify(event));
1084
+ return errors_1.EXIT.ok;
1085
+ }
1086
+ const sold = event.ticketTypes.reduce((n, t) => n + t.sold, 0);
1087
+ // Whether it is published is the draft read's to say, which the event's
1088
+ // managers and admins have: "not published yet", "live, changes not
1089
+ // published" or "live", as `event draft` says it. For anyone else, and
1090
+ // for an older Blocklive, only a state other than the ordinary one.
1091
+ const state = event.role === 'manager' || event.role === 'admin'
1092
+ ? await events().eventState(read, event.id)
1093
+ : undefined;
1094
+ const stands = state?.words ?? (event.status === 'active' ? '' : event.status);
1095
+ read.io.out(`${event.title}${stands ? ` (${stands})` : ''}`);
1096
+ const days = event.days ?? [];
1097
+ const multiDay = days.length >= 2;
1098
+ // A place picked from search is stored as an object: its name and
1099
+ // address are shown, never the JSON.
1100
+ const where = events().locationWords(event.location);
1101
+ read.io.out(`${(0, read_1.whenSpan)(event.startsAt, event.endsAt, event.timeZone, days)}${where ? ` · ${where}` : ''}`);
1102
+ read.io.out(`Tickets sold: ${sold} · checked in${multiDay ? ' (any day)' : ''}: ${event.checkedIn} · orders waiting: ${event.orders.pending}`);
1103
+ if (multiDay) {
1104
+ read.io.out('');
1105
+ for (const line of (0, read_1.table)([
1106
+ ['DAY', 'WHEN', 'IN'],
1107
+ ...days.map((d) => [
1108
+ `Day ${d.day}`,
1109
+ (0, read_1.whenSpan)(d.startsAt, d.endsAt, event.timeZone),
1110
+ String(d.checkedIn),
1111
+ ]),
1112
+ ]))
1113
+ read.io.out(line);
1114
+ }
1115
+ if (event.ticketTypes.length) {
1116
+ read.io.out('');
1117
+ for (const line of (0, read_1.table)([
1118
+ ['TICKET TYPE', 'PRICE', 'SOLD', 'OF'],
1119
+ ...event.ticketTypes.map((t) => [
1120
+ t.title,
1121
+ // As `tickets list` says a price: "free" for none. The
1122
+ // event's answer has no currency, so an amount stands alone.
1123
+ Number(t.price) > 0 ? String(t.price) : 'free',
1124
+ String(t.sold),
1125
+ String(t.supply),
1126
+ ]),
1127
+ ]))
1128
+ read.io.out(line);
1129
+ }
1130
+ const page = state?.published
1131
+ ? events().publicPage(read, event.slug)
1132
+ : undefined;
1133
+ if (event.path || page)
1134
+ read.io.out('');
1135
+ // The page guests see, once it is published; then where it is managed.
1136
+ if (page)
1137
+ read.io.out(`Public page: ${page}`);
1138
+ if (event.path)
1139
+ read.io.out(`On Blocklive: ${read.base}${event.path}`);
1140
+ return errors_1.EXIT.ok;
1141
+ }
1142
+ const CHECKIN = {
1143
+ checked_in: 'in',
1144
+ not_checked_in: 'not yet',
1145
+ not_issued: 'no ticket yet',
1146
+ unknown: '?',
1147
+ };
1148
+ async function listGuests(read, named) {
1149
+ const { rows, more, first } = await (0, read_1.pages)(read, `/events/${encodeURIComponent(named)}/guests`, (body) => body.guests ?? []);
1150
+ if (read.json) {
1151
+ read.io.out(JSON.stringify({ event: first?.event, guests: rows, more }));
1152
+ return errors_1.EXIT.ok;
1153
+ }
1154
+ if (!rows.length) {
1155
+ read.io.out('No guests yet.');
1156
+ return errors_1.EXIT.ok;
1157
+ }
1158
+ for (const line of (0, read_1.table)([
1159
+ ['GUEST', 'EMAIL', 'TICKET', 'ORDER', 'CHECKED IN'],
1160
+ ...rows.map((g) => [
1161
+ g.buyer ?? '',
1162
+ g.email ?? '',
1163
+ g.validDays?.length
1164
+ ? `${g.ticketType ?? ''} (${(0, read_1.dayWords)(g.validDays)})`
1165
+ : g.ticketType ?? '',
1166
+ g.orderState,
1167
+ g.daysIn?.length
1168
+ ? `${CHECKIN.checked_in} · ${(0, read_1.dayWords)(g.daysIn)}`
1169
+ : CHECKIN[g.checkin] ?? g.checkin,
1170
+ ]),
1171
+ ]))
1172
+ read.io.out(line);
1173
+ if (more)
1174
+ read.io.out('More guests: use --all, or --limit.');
1175
+ return errors_1.EXIT.ok;
1176
+ }