@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.
@@ -0,0 +1,956 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.publishEvent = exports.showDraft = exports.locationWords = exports.eventState = exports.publicPage = exports.editEvent = exports.createEvent = exports.zoned = exports.descriptionFile = exports.DESCRIPTION_FILE_MAX = void 0;
4
+ const fs_1 = require("fs");
5
+ const change_1 = require("../change");
6
+ const errors_1 = require("../errors");
7
+ const idempotency_1 = require("../idempotency");
8
+ const image_file_1 = require("../image-file");
9
+ const read_1 = require("../read");
10
+ const safe_1 = require("../safe");
11
+ const places_1 = require("./places");
12
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13
+ const PLACE = /^[A-Za-z0-9][A-Za-z0-9-]{0,199}$/;
14
+ // --description-file: UTF-8 text, at most 200 KB (a description is at most
15
+ // 50,000 characters, up to four bytes each).
16
+ exports.DESCRIPTION_FILE_MAX = 200000;
17
+ const linkOf = (read, linked) => (0, read_1.blocklivePath)(read.base, linked?.path);
18
+ // A sign-in on another profile is named in the commands the CLI suggests.
19
+ const profileFlag = (read) => read.profile === 'default' ? '' : ` --profile ${read.profile}`;
20
+ /** The description in a file: its text as it is, read and nothing else.
21
+ * One handle, opened without waiting (a pipe or a device isn't a file), its
22
+ * size taken from it and read through it, so the file checked is the file
23
+ * read. An empty one is refused: clearing it is `--description ""`. */
24
+ function descriptionFile(path) {
25
+ const said = (why) => (0, errors_1.usage)(`--description-file: ${why}`);
26
+ const tooBig = () => said(`${path} is over 200 KB; a description is at most 50,000 characters.`);
27
+ let fd;
28
+ try {
29
+ fd = (0, fs_1.openSync)(path, fs_1.constants.O_RDONLY | (fs_1.constants.O_NONBLOCK ?? 0));
30
+ }
31
+ catch {
32
+ throw said(`can't read ${path}.`);
33
+ }
34
+ let bytes;
35
+ try {
36
+ let info;
37
+ try {
38
+ info = (0, fs_1.fstatSync)(fd);
39
+ }
40
+ catch {
41
+ throw said(`can't read ${path}.`);
42
+ }
43
+ if (!info.isFile())
44
+ throw said(`${path} isn't a file.`);
45
+ if (info.size > exports.DESCRIPTION_FILE_MAX)
46
+ throw tooBig();
47
+ // One byte more than the most, to see a file that grew meanwhile.
48
+ const buffer = Buffer.alloc(exports.DESCRIPTION_FILE_MAX + 1);
49
+ let length = 0;
50
+ for (;;) {
51
+ let read;
52
+ try {
53
+ read = (0, fs_1.readSync)(fd, buffer, length, buffer.length - length, null);
54
+ }
55
+ catch {
56
+ throw said(`can't read ${path}.`);
57
+ }
58
+ if (!read)
59
+ break;
60
+ length += read;
61
+ if (length > exports.DESCRIPTION_FILE_MAX)
62
+ throw tooBig();
63
+ }
64
+ bytes = buffer.subarray(0, length);
65
+ }
66
+ finally {
67
+ (0, fs_1.closeSync)(fd);
68
+ }
69
+ let text;
70
+ try {
71
+ text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
72
+ }
73
+ catch {
74
+ throw said(`${path} isn't UTF-8 text.`);
75
+ }
76
+ if (text.includes('\u0000'))
77
+ throw said(`${path} isn't text.`);
78
+ // Line breaks as a browser's text box keeps them; a file's last one is
79
+ // the file's, not the description's.
80
+ const description = text
81
+ .replace(/^\ufeff/, '')
82
+ .replace(/\r\n?/g, '\n')
83
+ .replace(/\n$/, '');
84
+ if (!description.trim())
85
+ throw said(`${path} is empty. To clear the description on purpose, use --description "".`);
86
+ return description;
87
+ }
88
+ exports.descriptionFile = descriptionFile;
89
+ // This computer's time zone, as a browser's Create event takes the
90
+ // browser's; Blocklive refuses one it doesn't know, in words.
91
+ function localZone() {
92
+ try {
93
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;
94
+ }
95
+ catch {
96
+ return undefined;
97
+ }
98
+ }
99
+ function dropUndefined(out) {
100
+ return Object.fromEntries(Object.entries(out).filter(([, value]) => value !== undefined));
101
+ }
102
+ // What every plan and answer says about publishing.
103
+ const NOT_PUBLIC = "It isn't published: nobody can see it or get a ticket until it is published, on blocklive.io or with `blocklive event publish`.";
104
+ /** After a new event: what an agent can do next from here, and what a
105
+ * person does on blocklive.io. */
106
+ function nextSteps(read, made) {
107
+ const id = typeof made.id === 'string' && UUID.test(made.id)
108
+ ? made.id.toLowerCase()
109
+ : undefined;
110
+ const editor = (0, read_1.blocklivePath)(read.base, made.editor?.path)
111
+ ? made.editor?.path
112
+ : undefined;
113
+ const p = profileFlag(read);
114
+ return {
115
+ cli: id
116
+ ? [
117
+ {
118
+ command: `blocklive tickets add ${id} --title <title>${p}`,
119
+ does: 'Add a ticket type, free or with --price <amount> (it has General Admission already).',
120
+ },
121
+ {
122
+ command: `blocklive events edit ${id} --description-file <file> --location <text or link>${p}`,
123
+ does: 'Change its details, when and where.',
124
+ },
125
+ {
126
+ command: `blocklive events edit ${id} --cover <file>${p}`,
127
+ does: 'Set its cover image (a still PNG, JPEG or WebP; not with an unattended sign-in).',
128
+ },
129
+ {
130
+ command: `blocklive places search <text>${p}`,
131
+ does: 'Find its venue on Google Maps, then set it with `blocklive events edit <event> --place <place ID>` (not with an unattended sign-in).',
132
+ },
133
+ {
134
+ command: `blocklive event draft ${id}${p}`,
135
+ does: 'See its draft beside what is live.',
136
+ },
137
+ {
138
+ command: `blocklive event publish ${id}${p}`,
139
+ does: 'Publish it, when this sign-in may (Publish); else a person publishes it on blocklive.io.',
140
+ },
141
+ ]
142
+ : [],
143
+ onBlocklive: {
144
+ ...(editor ? { path: editor } : {}),
145
+ does: ['cover video', 'payment account', 'publish'],
146
+ },
147
+ };
148
+ }
149
+ const MONTHS = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ');
150
+ const LOCAL = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
151
+ // A time in Blocklive's ISO 8601 where the event is (`starts`, `ends`):
152
+ // as people read it (1 Dec 2026, 19:00) and its offset (UTC+04:00).
153
+ function local(iso) {
154
+ const found = typeof iso === 'string' ? LOCAL.exec(iso) : null;
155
+ const month = found && MONTHS[Number(found[2]) - 1];
156
+ if (!found || !month)
157
+ return undefined;
158
+ const [, y, , d, h, mi, s, offset] = found;
159
+ return {
160
+ at: `${Number(d)} ${month} ${y}, ${h}:${mi}${s && s !== '00' ? `:${s}` : ''}`,
161
+ offset: `UTC${offset === 'Z' ? '' : offset}`,
162
+ };
163
+ }
164
+ /** A time as people read it, with its offset: 1 Dec 2026, 19:00
165
+ * (UTC+04:00). From Blocklive's own ISO 8601 where the event is, so it is
166
+ * the time Blocklive keeps; else from the milliseconds, by the zone's name. */
167
+ function zoned(at, iso, zone) {
168
+ const found = local(iso);
169
+ if (found)
170
+ return `${found.at} (${found.offset})`;
171
+ const shown = (0, read_1.when)(at, zone);
172
+ return shown ? `${shown} (${zone || 'UTC'})` : '(none)';
173
+ }
174
+ exports.zoned = zoned;
175
+ /** From a start to an end, the offset said once when they share it. */
176
+ function span(from, to, zone) {
177
+ const start = local(from[1]);
178
+ const end = local(to[1]);
179
+ if (start && end)
180
+ return start.offset === end.offset
181
+ ? `${start.at} – ${end.at} (${zone ? `${zone}, ` : ''}${start.offset})`
182
+ : `${start.at} (${start.offset}) – ${end.at} (${end.offset})${zone ? `, ${zone}` : ''}`;
183
+ return `${(0, read_1.when)(from[0], zone)} – ${(0, read_1.when)(to[0], zone)} (${zone || 'UTC'})`;
184
+ }
185
+ function showCreatePlan(read, plan) {
186
+ const out = read.io.out;
187
+ const zone = plan.timeZone ?? null;
188
+ out(`Create an event at ${plan.team?.name ?? 'the team'}, as a draft:`);
189
+ out(` ${plan.title}`);
190
+ out(` ${span([plan.startsAt, plan.starts], [plan.endsAt, plan.ends], zone)}`);
191
+ const tickets = (plan.ticketTypes ?? [])
192
+ .map((t) => `${t.title} (${t.price > 0 ? t.price : 'free'}, ${t.supply})`)
193
+ .join(', ');
194
+ out(` Set up as blocklive.io sets up a new event: ${tickets ? `the ticket type ${tickets}, ` : ''}the checkout questions Email and Full name, reminder emails a day and an hour before it starts, and the team as its organiser.`);
195
+ out(NOT_PUBLIC);
196
+ }
197
+ async function createEvent(read, rest) {
198
+ const args = rest[0] === 'create' ? rest.slice(1) : rest;
199
+ if (args.length)
200
+ throw (0, errors_1.usage)('Name the team with --team: blocklive events create --team <team> --title "…".');
201
+ const v = read.values;
202
+ const team = v.team;
203
+ if (team === undefined || !PLACE.test(team))
204
+ throw (0, errors_1.usage)('Name the team, by its ID or slug: --team <team> (`team.slug` in `events list --json`).');
205
+ if (v.title !== undefined && !v.title.trim())
206
+ throw (0, errors_1.usage)("--title is the event's name: it can't be empty.");
207
+ const body = dropUndefined({
208
+ title: v.title,
209
+ start: (0, change_1.time)(v.starts, '--starts'),
210
+ end: (0, change_1.time)(v.ends, '--ends'),
211
+ timeZone: v['time-zone'] ?? localZone(),
212
+ });
213
+ return (0, change_1.change)(read, {
214
+ path: `/teams/${encodeURIComponent(team)}/events`,
215
+ body,
216
+ question: 'Create this event?',
217
+ show: (plan) => showCreatePlan(read, plan),
218
+ done: (made, key, tried) => {
219
+ const next = nextSteps(read, made);
220
+ if (read.json) {
221
+ read.io.out((0, change_1.answered)({ ...made, next }, key, tried));
222
+ return;
223
+ }
224
+ const out = read.io.out;
225
+ out(`Created ${made.title} at ${made.team?.name ?? 'the team'}, as a draft${made.replayed
226
+ ? ' (sent before with this key: made once)'
227
+ : ''}. ${NOT_PUBLIC}`);
228
+ for (const line of (0, read_1.table)([
229
+ [' ID', made.id ?? ''],
230
+ [' Slug', made.slug ?? ''],
231
+ ].filter(([, value]) => value)))
232
+ out(line);
233
+ const editor = linkOf(read, made.editor);
234
+ if (editor)
235
+ out(` Editor: ${editor}`);
236
+ if (next.cli.length) {
237
+ out('Next, from here:');
238
+ for (const step of next.cli)
239
+ out(` ${step.command}`);
240
+ }
241
+ out(`On blocklive.io, a person picks the payment account${editor ? `: ${editor}` : '.'}`);
242
+ },
243
+ });
244
+ }
245
+ exports.createEvent = createEvent;
246
+ // The draft's fields as the CLI names them, in the editor's order.
247
+ const FIELDS = [
248
+ ['title', 'title'],
249
+ ['shortDescription', 'subtitle'],
250
+ ['description', 'description'],
251
+ ['startsAt', 'starts'],
252
+ ['endsAt', 'ends'],
253
+ ['timeZone', 'time zone'],
254
+ ['address', 'location'],
255
+ ['locationType', 'online or in person'],
256
+ ['hideLocation', 'location shown'],
257
+ ];
258
+ /** A description in a line: its first 60 characters, and its length when
259
+ * there is more (Blocklive's: an answer has at most its first 300). */
260
+ function descriptionLine(d) {
261
+ if (d === null || d === undefined)
262
+ return '(none)';
263
+ const text = typeof d === 'string' ? d : String(d.text ?? '');
264
+ const length = typeof d === 'string' ? d.length : Number(d.length) || text.length;
265
+ if (!length)
266
+ return '(empty)';
267
+ return (typeof d === 'object' && d.truncated) || text.length > 60
268
+ ? `${text.slice(0, 60)}… (${length.toLocaleString('en-GB')} characters)`
269
+ : text;
270
+ }
271
+ function valueOf(d, key) {
272
+ if (!d)
273
+ return '';
274
+ const zone = d.timeZone ?? null;
275
+ switch (key) {
276
+ case 'startsAt':
277
+ return zoned(d.startsAt, d.starts, zone);
278
+ case 'endsAt':
279
+ return zoned(d.endsAt, d.ends, zone);
280
+ case 'description':
281
+ return descriptionLine(d.description);
282
+ case 'locationType':
283
+ return d.locationType === 'virtual' ? 'online' : 'in person';
284
+ case 'hideLocation':
285
+ return d.hideLocation
286
+ ? 'only to people who registered'
287
+ : 'to everyone';
288
+ case 'timeZone':
289
+ return d.timeZone ?? '(none)';
290
+ default:
291
+ return d[key] || '(none)';
292
+ }
293
+ }
294
+ // What the options ask for, as the route takes it.
295
+ function editFields(read) {
296
+ const v = read.values;
297
+ if (v.description !== undefined && v['description-file'] !== undefined)
298
+ throw (0, errors_1.usage)('Use --description or --description-file, not both.');
299
+ if (v.title !== undefined && !v.title.trim())
300
+ throw (0, errors_1.usage)("--title is the event's name: it can't be empty.");
301
+ return dropUndefined({
302
+ title: v.title,
303
+ shortDescription: v.subtitle,
304
+ description: v['description-file'] !== undefined
305
+ ? descriptionFile(v['description-file'])
306
+ : v.description,
307
+ start: (0, change_1.time)(v.starts, '--starts'),
308
+ end: (0, change_1.time)(v.ends, '--ends'),
309
+ timeZone: v['time-zone'],
310
+ address: v.location,
311
+ hideLocation: (0, change_1.either)(read, 'hide-location', 'show-location'),
312
+ });
313
+ }
314
+ // What a change does: each field that differs, before and after. Decided on
315
+ // the dry run's answer as Blocklive sent it, never as the terminal shows it:
316
+ // cleaning turns line breaks into spaces and drops invisible characters, so
317
+ // a change of only those would look like none. A description is compared by
318
+ // its SHA-256 and length (an answer never holds the whole of a long one).
319
+ const differing = (sent) => FIELDS.filter(([key]) => JSON.stringify(sent.before?.[key] ?? null) !==
320
+ JSON.stringify(sent.draft?.[key] ?? null));
321
+ function showEditPlan(read, plan, changes) {
322
+ const out = read.io.out;
323
+ out(`Change the draft of ${plan.event.title}:`);
324
+ for (const line of (0, read_1.table)(changes.map(([key, name]) => {
325
+ const before = valueOf(plan.before, key);
326
+ const after = valueOf(plan.draft, key);
327
+ // Different as sent, alike as shown: only spacing, line breaks
328
+ // or invisible characters change.
329
+ return [
330
+ ` ${name}`,
331
+ before,
332
+ '→',
333
+ after === before
334
+ ? `${after} (only its spacing or line breaks change)`
335
+ : after,
336
+ ];
337
+ })))
338
+ out(line);
339
+ const moved = plan.moved ?? { reminders: 0, ticketSales: 0 };
340
+ if (moved.reminders)
341
+ out(moved.reminders === 1
342
+ ? ' 1 reminder email moves with the start, keeping its time before it.'
343
+ : ` ${moved.reminders} reminder emails move with the start, keeping their time before it.`);
344
+ if (moved.ticketSales)
345
+ out(moved.ticketSales === 1
346
+ ? ' 1 ticket sale that ended with the event ends with it again.'
347
+ : ` ${moved.ticketSales} ticket sales that ended with the event end with it again.`);
348
+ const link = linkOf(read, plan.publish);
349
+ out(`Nothing is public until the event is published, on blocklive.io${link ? ` (${link})` : ''} or with \`blocklive event publish\`.`);
350
+ }
351
+ /** `events edit <event> --cover <file>`: the event draft's cover image. The
352
+ * file is sent as it is; Blocklive checks it, stores it and puts it in the
353
+ * draft, after the plan and a yes, once, as every change. */
354
+ async function setCover(read, event, file) {
355
+ const bytes = (0, image_file_1.imageFile)(file, '--cover');
356
+ const path = `/images/events/${encodeURIComponent(event)}/cover`;
357
+ const published = (plan) => {
358
+ const link = (0, read_1.blocklivePath)(read.base, plan.path);
359
+ return `on blocklive.io${link ? ` (${link})` : ''} or with \`blocklive event publish\``;
360
+ };
361
+ return (0, change_1.change)(read, {
362
+ path,
363
+ body: {},
364
+ send: (key, options) => read.client.upload(path, bytes, key, options),
365
+ question: 'Set this cover?',
366
+ unchanged: (sent) => sent.changed === false,
367
+ nothing: (plan) => `The draft of ${plan.event.title} has that cover already: nothing to change.`,
368
+ show: (plan) => {
369
+ read.io.out(`Set the cover of ${plan.event.title}, in its draft:`);
370
+ read.io.out(` ${(0, image_file_1.imageWords)(plan.image)}`);
371
+ read.io.out(`It goes live only when the event is published, ${published(plan)}.`);
372
+ },
373
+ done: (done, key, tried) => {
374
+ if (read.json) {
375
+ read.io.out((0, change_1.answered)(done, key, tried));
376
+ return;
377
+ }
378
+ read.io.out(done.changed === false && !done.replayed
379
+ ? `Nothing changed: the draft of ${done.event.title} has that cover already.`
380
+ : `Done: the draft of ${done.event.title} has that cover${done.replayed
381
+ ? ' (sent before with this key: done once)'
382
+ : ''}.`);
383
+ read.io.out(`Publish the event to put it live, ${published(done)}.`);
384
+ },
385
+ });
386
+ }
387
+ // A Google place ID, as `places search` shows it.
388
+ const PLACE_ID = /^[A-Za-z0-9_-]{10,300}$/;
389
+ /** `events edit <event> --place <Google place ID>`: the event draft's place
390
+ * on the map. Only the ID is sent: Blocklive asks Google for the place and
391
+ * builds what it stores itself. After the plan and a yes, once, as every
392
+ * change. */
393
+ async function setPlace(read, event, id) {
394
+ if (!PLACE_ID.test(id))
395
+ throw (0, errors_1.usage)('--place takes a Google place ID, as `blocklive places search <text>` shows it.');
396
+ const published = (plan) => {
397
+ const link = (0, read_1.blocklivePath)(read.base, plan.path);
398
+ return `on blocklive.io${link ? ` (${link})` : ''} or with \`blocklive event publish\``;
399
+ };
400
+ const lines = (plan) => {
401
+ for (const line of (0, read_1.table)([
402
+ [' Place', plan.place?.name ?? ''],
403
+ [' Address', plan.place?.address ?? ''],
404
+ [' Map', plan.place?.mapsLink ?? ''],
405
+ ].filter(([, value]) => value)))
406
+ read.io.out(line);
407
+ };
408
+ return (0, change_1.change)(read, {
409
+ path: `/events/${encodeURIComponent(event)}/place`,
410
+ body: { place: id },
411
+ question: 'Set this place?',
412
+ unchanged: (sent) => sent.changed === false,
413
+ nothing: (plan) => `The draft of ${plan.event.title} has that place already: nothing to change.`,
414
+ show: (plan) => {
415
+ read.io.out(`Set the place of ${plan.event.title}, in its draft:`);
416
+ lines(plan);
417
+ if (plan.was?.address)
418
+ read.io.out(plan.was.type === 'virtual'
419
+ ? `It replaces its online link (${plan.was.address}): the event becomes one in person.`
420
+ : `It replaces: ${plan.was.address}`);
421
+ read.io.out(`It goes live only when the event is published, ${published(plan)}.`);
422
+ },
423
+ done: (done, key, tried) => {
424
+ if (read.json) {
425
+ read.io.out((0, change_1.answered)(done, key, tried));
426
+ return;
427
+ }
428
+ if (done.changed === false && !done.replayed)
429
+ read.io.out(`Nothing changed: the draft of ${done.event.title} has that place already.`);
430
+ else
431
+ read.io.out(`Done: the draft of ${done.event.title} has that place${done.replayed
432
+ ? ' (sent before with this key: done once)'
433
+ : ''}.`);
434
+ read.io.out(`Publish the event to put it live, ${published(done)}.`);
435
+ // Setting a place asks Google once: what is left today, as
436
+ // `places search` says it.
437
+ const remaining = (0, places_1.lookupsLeft)(done.lookupsLeft);
438
+ if (remaining)
439
+ read.io.out(remaining);
440
+ },
441
+ });
442
+ }
443
+ async function editEvent(read, rest) {
444
+ const event = (0, read_1.named)(rest, 'edit', 'event');
445
+ const body = editFields(read);
446
+ // A place from the map goes on its own too: Blocklive builds it from
447
+ // Google's answer for the ID (never an unattended sign-in).
448
+ if (read.values.place !== undefined) {
449
+ if (Object.keys(body).length || read.values.cover !== undefined)
450
+ throw (0, errors_1.usage)('--place goes on its own: set the place in one command, and change the rest in another.');
451
+ return setPlace(read, event, read.values.place);
452
+ }
453
+ // An image goes on its own: it is another change, with its own rules
454
+ // (never an unattended sign-in), sent another way.
455
+ if (read.values.cover !== undefined) {
456
+ if (Object.keys(body).length)
457
+ throw (0, errors_1.usage)('--cover goes on its own: set the cover in one command, and change the rest in another.');
458
+ return setCover(read, event, read.values.cover);
459
+ }
460
+ if (!Object.keys(body).length)
461
+ throw (0, errors_1.usage)('Say what to change: --title, --subtitle, --description or --description-file, --starts, --ends, --time-zone, --location, --hide-location or --show-location; or --cover <file>, or --place <place ID>.');
462
+ let changes = [];
463
+ return (0, change_1.change)(read, {
464
+ path: `/events/${encodeURIComponent(event)}/draft`,
465
+ body,
466
+ question: 'Make these changes?',
467
+ unchanged: (sent) => !(changes = differing(sent)).length,
468
+ nothing: (plan) => `The draft of ${plan.event.title} is like that already: nothing to change.`,
469
+ show: (plan) => showEditPlan(read, plan, changes),
470
+ done: (done, key, tried) => {
471
+ if (read.json) {
472
+ read.io.out((0, change_1.answered)(done, key, tried));
473
+ return;
474
+ }
475
+ const link = linkOf(read, done.publish);
476
+ read.io.out(`Changed the draft of ${done.event.title}${done.replayed
477
+ ? ' (sent before with this key: done once)'
478
+ : ''}.`);
479
+ read.io.out(`It goes live when it is published, on blocklive.io${link ? ` (${link})` : ''} or with \`blocklive event publish\`.`);
480
+ },
481
+ });
482
+ }
483
+ exports.editEvent = editEvent;
484
+ const NOT_PUBLISHED = '(not yet published)';
485
+ /** A ticket type's side in a line: its price, and whether it is removed. */
486
+ function ticketWords(side) {
487
+ if (!side)
488
+ return '';
489
+ if (side.removed)
490
+ return '(removed)';
491
+ const price = Number(side.price) || 0;
492
+ const priced = price > 0
493
+ ? `${Number.isInteger(price) ? price : price.toFixed(2)} ${side.currency ?? ''}`.trim()
494
+ : 'free';
495
+ return side.onSale === false ? `${priced}, not on sale` : priced;
496
+ }
497
+ /** A place in a line: its name, its address, its map link. */
498
+ function placeWords(place) {
499
+ if (!place)
500
+ return '(none)';
501
+ const named = [place.name, place.address]
502
+ .filter((part) => !!part)
503
+ .filter((part, i, all) => all.indexOf(part) === i)
504
+ .join(', ');
505
+ return [
506
+ named || '(no name)',
507
+ place.mapsLink ? `map: ${place.mapsLink}` : '',
508
+ ]
509
+ .filter(Boolean)
510
+ .join(' ');
511
+ }
512
+ /**
513
+ * The cover, the place and the ticket types, draft beside live: what
514
+ * `event draft` adds under its table, and what `event publish --dry-run`
515
+ * lists as going live. Nothing for an answer without them.
516
+ */
517
+ function shownLines(answer, goingLive = false) {
518
+ const lines = [];
519
+ const live = (value, words) => !answer.published || value === null || value === undefined
520
+ ? answer.published
521
+ ? '(none)'
522
+ : NOT_PUBLISHED
523
+ : words(value);
524
+ // What differs from what is live, on a published event: Blocklive's
525
+ // `changed` names only the fields of the table above, so the CLI compares
526
+ // the two sides of these itself.
527
+ const differs = (draft, was) => answer.published &&
528
+ draft !== null &&
529
+ draft !== undefined &&
530
+ was !== null &&
531
+ was !== undefined &&
532
+ JSON.stringify(draft) !== JSON.stringify(was);
533
+ const pair = (name, draft, was, changed) => {
534
+ lines.push(`${name}:${changed ? ' (changed)' : ''}`);
535
+ lines.push(` ${goingLive ? 'Goes live' : 'Draft'}: ${draft}`);
536
+ lines.push(` Live${goingLive ? ' now' : ''}: ${draft === was ? '(the same)' : was}`);
537
+ };
538
+ if (answer.cover) {
539
+ pair('Cover', answer.cover.draft?.image || '(none)', live(answer.cover.live, (c) => c.image || '(none)'), differs(answer.cover.draft, answer.cover.live));
540
+ }
541
+ if (answer.place) {
542
+ // A place set or cleared is a change too: null on one side only.
543
+ // Not said for a location shown only to people who registered, or
544
+ // an online event: what is live of those is less than the draft
545
+ // (the city alone, or nothing), whatever the draft holds.
546
+ const { draft, live: was } = answer.place;
547
+ const partly = [answer.draft, answer.live].some((side) => side?.hideLocation === true || side?.locationType === 'virtual');
548
+ pair('Place', placeWords(draft), live(was, placeWords), answer.published &&
549
+ !!answer.draft &&
550
+ !partly &&
551
+ JSON.stringify(draft ?? null) !== JSON.stringify(was ?? null));
552
+ }
553
+ if (answer.ticketTypes) {
554
+ lines.push('Ticket types:');
555
+ if (!answer.ticketTypes.length)
556
+ lines.push(' (none)');
557
+ for (const line of (0, read_1.table)([
558
+ ...(answer.ticketTypes.length
559
+ ? [
560
+ [
561
+ ' TICKET TYPE',
562
+ goingLive ? 'GOES LIVE' : 'DRAFT',
563
+ 'LIVE',
564
+ '',
565
+ ],
566
+ ]
567
+ : []),
568
+ ...answer.ticketTypes.map((t) => [
569
+ ` ${t.draft?.title ?? t.live?.title ?? '(no name)'}`,
570
+ t.draft ? ticketWords(t.draft) : '(no draft)',
571
+ t.live ? ticketWords(t.live) : NOT_PUBLISHED,
572
+ differs(t.draft, t.live) ? 'changed' : '',
573
+ ]),
574
+ ]))
575
+ lines.push(line.trimEnd());
576
+ for (const t of answer.ticketTypes) {
577
+ const art = t.draft?.image ?? null;
578
+ if (!art || t.draft?.removed)
579
+ continue;
580
+ lines.push(` Art, ${t.draft?.title ?? '(no name)'}: ${art}${!t.live
581
+ ? ` ${NOT_PUBLISHED}`
582
+ : (t.live.image ?? null) === art
583
+ ? ''
584
+ : ` (live: ${t.live.image ?? 'none'})`}`);
585
+ }
586
+ }
587
+ return lines;
588
+ }
589
+ /** An event's public page, the one guests see: on the Blocklive the CLI is
590
+ * signed in to, never a fixed host. */
591
+ function publicPage(read, slug) {
592
+ return typeof slug === 'string' &&
593
+ /^[A-Za-z0-9][A-Za-z0-9-]{0,199}$/.test(slug)
594
+ ? (0, read_1.blocklivePath)(read.base, `/event/${slug}`)
595
+ : undefined;
596
+ }
597
+ exports.publicPage = publicPage;
598
+ /**
599
+ * Where an event stands, for `event show`: "not published yet", "live,
600
+ * changes not published" or "live", as `event draft` says it. Asked of the
601
+ * draft read, which is for the event's managers and admins; undefined when
602
+ * it can't be read.
603
+ */
604
+ async function eventState(read, event) {
605
+ try {
606
+ const d = await read.client.get(`/events/${encodeURIComponent(event)}/draft`);
607
+ if (typeof d?.published !== 'boolean')
608
+ return undefined;
609
+ return { words: stateOf(d), published: d.published };
610
+ }
611
+ catch (error) {
612
+ if (error instanceof errors_1.CliError)
613
+ return undefined;
614
+ throw error;
615
+ }
616
+ }
617
+ exports.eventState = eventState;
618
+ /**
619
+ * A stored location as people read it. Blocklive keeps a place picked from
620
+ * search as a JSON object (its name, its address, its map link, its parts):
621
+ * its name and address are shown, never the JSON. Typed text is shown as
622
+ * it is. Nothing for an object without a name or an address.
623
+ */
624
+ function locationWords(location) {
625
+ if (typeof location !== 'string')
626
+ return '';
627
+ const text = location.trim();
628
+ if (!/^[{[]/.test(text))
629
+ return /^(null|"")?$/.test(text) ? '' : text;
630
+ let place;
631
+ try {
632
+ place = JSON.parse(text);
633
+ }
634
+ catch {
635
+ return '';
636
+ }
637
+ if (!place || typeof place !== 'object' || Array.isArray(place))
638
+ return '';
639
+ const of = place;
640
+ const named = of.displayName ?? of.display_name;
641
+ const name = typeof named === 'string'
642
+ ? named
643
+ : named && typeof named === 'object'
644
+ ? named.text
645
+ : undefined;
646
+ const address = of.formattedAddress ?? of.formatted_address;
647
+ return [name, address]
648
+ .filter((part) => typeof part === 'string' && !!part)
649
+ .filter((part, i, all) => all.indexOf(part) === i)
650
+ .map((part) => (0, safe_1.cleanText)(part))
651
+ .join(', ');
652
+ }
653
+ exports.locationWords = locationWords;
654
+ function stateOf(d) {
655
+ if (!d.published)
656
+ return 'not published yet';
657
+ return d.unpublishedChanges ? 'live, changes not published' : 'live';
658
+ }
659
+ // A whole description, line by line as it was typed, each line cleaned.
660
+ function descriptionLines(full) {
661
+ return full
662
+ .split(/\r\n|[\n\r\u2028\u2029]/)
663
+ .map((line) => ` ${(0, safe_1.cleanText)(line)}`);
664
+ }
665
+ async function showDraft(read, rest) {
666
+ const event = (0, read_1.named)(rest, 'draft', 'event');
667
+ // --full: each description whole. Read as sent, so its line breaks
668
+ // stay; every line is cleaned as it is printed.
669
+ const sent = await read.client.get(`/events/${encodeURIComponent(event)}/draft`, read.values.full ? { description: 'full' } : undefined, { raw: true });
670
+ if (read.json) {
671
+ read.io.out(JSON.stringify(sent));
672
+ return errors_1.EXIT.ok;
673
+ }
674
+ const answer = (0, safe_1.cleanData)(sent);
675
+ const out = read.io.out;
676
+ out(`${answer.event.title} (${stateOf(answer)})`);
677
+ const editor = linkOf(read, answer.editor);
678
+ if (!answer.draft) {
679
+ out(`It has no draft yet: open it in the editor on blocklive.io${editor ? `: ${editor}` : '.'}`);
680
+ return errors_1.EXIT.ok;
681
+ }
682
+ const changed = new Set(answer.changed ?? []);
683
+ for (const line of (0, read_1.table)([
684
+ ['', 'DRAFT', 'LIVE', ''],
685
+ ...FIELDS.map(([key, name]) => [
686
+ name,
687
+ valueOf(answer.draft, key),
688
+ answer.published ? valueOf(answer.live, key) : '',
689
+ changed.has(key) && answer.published ? 'changed' : '',
690
+ ]),
691
+ ]))
692
+ out(line);
693
+ const more = shownLines(answer);
694
+ if (more.length)
695
+ out('');
696
+ for (const line of more)
697
+ out(line);
698
+ if (read.values.full) {
699
+ // As sent, whole; a description without its whole text (an older
700
+ // Blocklive) as the table has it.
701
+ const told = (heading, d, shown) => {
702
+ out('');
703
+ const full = d?.description?.full;
704
+ if (typeof full === 'string') {
705
+ out(`${heading}:`);
706
+ for (const line of descriptionLines(full))
707
+ out(line);
708
+ }
709
+ else
710
+ out(`${heading}: ${descriptionLine(shown?.description)}`);
711
+ };
712
+ told('Description', sent.draft, answer.draft);
713
+ if (answer.published && changed.has('description'))
714
+ told('Live description', sent.live, answer.live);
715
+ }
716
+ out('');
717
+ if (editor)
718
+ out(`Editor: ${editor}`);
719
+ const publish = linkOf(read, answer.publish);
720
+ out(answer.unpublishedChanges
721
+ ? `To put it live, publish it on blocklive.io${publish ? ` (${publish})` : ''} or with \`blocklive event publish\`.`
722
+ : 'Nothing to publish: what is live is the draft.');
723
+ return errors_1.EXIT.ok;
724
+ }
725
+ exports.showDraft = showDraft;
726
+ // Every 2 seconds for up to 3 minutes.
727
+ const POLL_MS = 2000;
728
+ const POLLS = 90;
729
+ const FAILED = "The publish didn't go through. Nothing went live.";
730
+ /** The draft's changed fields as people read them: Title, Starts. */
731
+ function changedWords(changed) {
732
+ return (changed ?? [])
733
+ .map((key) => FIELDS.find(([k]) => k === key)?.[1] ?? key)
734
+ .map((name) => name.charAt(0).toUpperCase() + name.slice(1))
735
+ .join(', ');
736
+ }
737
+ function showPublishPlan(read, plan) {
738
+ const out = read.io.out;
739
+ out(`Publish ${plan.event.title}:`);
740
+ const first = plan.publishing?.first ?? !plan.published;
741
+ if (first)
742
+ out(' It has never been published: publishing makes it public, with its tickets and prices.');
743
+ else {
744
+ const words = changedWords(plan.changed);
745
+ out(words
746
+ ? ` Publishing makes these changes public: ${words}.`
747
+ : ' Publishing makes its changes public: its tickets or other details changed.');
748
+ }
749
+ for (const line of shownLines(plan, true))
750
+ out(` ${line}`);
751
+ const preview = linkOf(read, plan.preview);
752
+ if (preview)
753
+ out(` Preview: ${preview}`);
754
+ out('This goes live for everyone.');
755
+ }
756
+ /** One publish as --json prints it: one object a run. */
757
+ function publishJson(answer, published, key, more = {}) {
758
+ const p = answer.publishing;
759
+ return JSON.stringify({
760
+ event: answer.event,
761
+ published,
762
+ first: p?.first ?? !answer.published,
763
+ changed: answer.changed,
764
+ preview: answer.preview,
765
+ editor: answer.editor,
766
+ publish: answer.publish,
767
+ publishing: p
768
+ ? {
769
+ id: p.id ?? null,
770
+ status: p.status ?? null,
771
+ first: p.first ?? null,
772
+ startedAt: p.startedAt ?? null,
773
+ finished: !!p.finished,
774
+ reason: p.reason ?? null,
775
+ }
776
+ : null,
777
+ ...(answer.replayed ? { replayed: true } : {}),
778
+ ...(answer.alreadyFinished ? { alreadyFinished: true } : {}),
779
+ idempotencyKey: key,
780
+ ...more,
781
+ });
782
+ }
783
+ /** A refusal that leaves publishing to a person on blocklive.io (no
784
+ * Publish on this sign-in; an event published from the organiser's own
785
+ * wallet): with where they publish it, when the draft says. */
786
+ async function toBlocklive(read, event, error) {
787
+ if (!(error instanceof errors_1.CliError) ||
788
+ !(error.code === 'forbidden' ||
789
+ (error.code === 'refused' && /own wallet/i.test(error.message))))
790
+ return error;
791
+ let link;
792
+ try {
793
+ const draft = await read.client.get(`/events/${encodeURIComponent(event)}/draft`);
794
+ link = linkOf(read, draft.publish) ?? linkOf(read, draft.editor);
795
+ }
796
+ catch {
797
+ return error;
798
+ }
799
+ if (!link)
800
+ return error;
801
+ if (!read.json)
802
+ read.io.out(`A person publishes it on blocklive.io: ${link}`);
803
+ return new errors_1.CliError(error.message, error.exitCode, error.code, error.requestId, { ...error.details, publishUrl: link }, error.status);
804
+ }
805
+ async function publishEvent(read, rest) {
806
+ const event = (0, read_1.named)(rest, 'publish', 'event');
807
+ const path = `/events/${encodeURIComponent(event)}/publish`;
808
+ const v = read.values;
809
+ if (v.finish !== undefined) {
810
+ if (!UUID.test(v.finish))
811
+ throw (0, errors_1.usage)('--finish takes the publish ID the CLI printed, a UUID like 7b1e4c2a-0f3d-4e5b-9a61-2c8d0e4f6a17.');
812
+ if (v['dry-run'])
813
+ throw (0, errors_1.usage)('--finish finishes a publish already started: it has no dry run.');
814
+ const id = v.finish.toLowerCase();
815
+ const key = (0, idempotency_1.idempotencyKey)(v['idempotency-key']);
816
+ const state = await read.client.get(`${path}/${id}`);
817
+ return follow(read, event, state, key, undefined);
818
+ }
819
+ const given = v['idempotency-key'] !== undefined;
820
+ const key = (0, idempotency_1.idempotencyKey)(v['idempotency-key']);
821
+ const planOnly = !!v['dry-run'] || (read.json && !v.yes);
822
+ // Progress beside --json's one object goes to stderr.
823
+ const say = read.json ? read.io.err : read.io.out;
824
+ let plan;
825
+ let tried;
826
+ try {
827
+ plan = await read.client.post(path, { dryRun: true });
828
+ }
829
+ catch (error) {
830
+ // A run with its key may be a publish that key started already
831
+ // (now refused as being published, or as nothing to publish): only
832
+ // the start itself, sent with it, gets Blocklive's answer for it.
833
+ if (!given ||
834
+ planOnly ||
835
+ !(error instanceof errors_1.CliError) ||
836
+ error instanceof errors_1.NoAnswer ||
837
+ error.code !== 'refused')
838
+ throw await toBlocklive(read, event, error);
839
+ tried = error;
840
+ }
841
+ if (plan) {
842
+ if (!read.json)
843
+ showPublishPlan(read, plan);
844
+ if (planOnly) {
845
+ if (read.json)
846
+ read.io.out(publishJson(plan, false, key, {
847
+ dryRun: true,
848
+ // What goes live, beside what is live now.
849
+ ...(plan.cover ? { cover: plan.cover } : {}),
850
+ ...(plan.place ? { place: plan.place } : {}),
851
+ ...(plan.ticketTypes
852
+ ? { ticketTypes: plan.ticketTypes }
853
+ : {}),
854
+ }));
855
+ else
856
+ read.io.out('Dry run: nothing was published.');
857
+ return errors_1.EXIT.ok;
858
+ }
859
+ if (!(await (0, change_1.confirm)(read, `Publish ${plan.event.title}?`, `publish ${plan.event.title}`))) {
860
+ read.io.out('Nothing was published.');
861
+ return errors_1.EXIT.ok;
862
+ }
863
+ say(`Publishing ${plan.event.title}…`);
864
+ }
865
+ else {
866
+ if (!read.json) {
867
+ read.io.out(`Trying it first was refused: ${tried.message}`);
868
+ read.io.out(`It is sent with its idempotency key (${key}) all the same: if that key started it before, Blocklive answers how it stands; if not, it refuses it again.`);
869
+ }
870
+ if (!(await (0, change_1.confirm)(read, 'Send it with its key?'))) {
871
+ read.io.out('Nothing was published.');
872
+ return errors_1.EXIT.ok;
873
+ }
874
+ }
875
+ let started;
876
+ try {
877
+ started = await (0, change_1.send)(read, path, {}, key);
878
+ }
879
+ catch (error) {
880
+ if (tried && error instanceof errors_1.CliError && error.code === 'refused')
881
+ throw new errors_1.CliError(`This key didn't start it before (or not in the last 24 hours), and Blocklive refuses it now: ${error.message}`, error.exitCode, error.code, error.requestId, { idempotencyKey: key });
882
+ throw await toBlocklive(read, event, error);
883
+ }
884
+ return follow(read, event, started, key, (0, idempotency_1.idempotencyKey)(undefined));
885
+ }
886
+ exports.publishEvent = publishEvent;
887
+ /** Waits for a publish to go through (unless --no-wait), then finishes it.
888
+ * `key` is the run's (the start's, or with --finish the finish's own);
889
+ * `finishKey` a new one for the finish after a start. */
890
+ async function follow(read, event, first, key, finishKey) {
891
+ const out = read.io.out;
892
+ const path = `/events/${encodeURIComponent(event)}/publish`;
893
+ let state = first;
894
+ const id = state.publishing?.id;
895
+ if (typeof id !== 'string' || !UUID.test(id))
896
+ throw new errors_1.CliError("Blocklive's answer named no publish, so it isn't known how it stands. Run `blocklive event draft` to see whether it went live.");
897
+ const title = state.event.title;
898
+ for (let polls = 0;; polls += 1) {
899
+ const status = state.publishing?.status;
900
+ if (status === 'processed')
901
+ break;
902
+ if (status === 'failed_to_process') {
903
+ const reason = state.publishing?.reason || FAILED;
904
+ if (read.json)
905
+ out(publishJson(state, false, key));
906
+ else
907
+ read.io.err(reason);
908
+ return errors_1.EXIT.error;
909
+ }
910
+ if (read.values['no-wait'] || polls >= POLLS) {
911
+ const command = `blocklive event publish ${event} --finish ${id.toLowerCase()}${profileFlag(read)}`;
912
+ if (read.json)
913
+ out(publishJson(state, false, key, { finish: command }));
914
+ else {
915
+ out(`${title} is still being published${read.values['no-wait'] ? '' : ' after 3 minutes'}. Nothing is live until it is finished: ${command}`);
916
+ }
917
+ return errors_1.EXIT.partial;
918
+ }
919
+ await read.io.wait(POLL_MS);
920
+ try {
921
+ state = await read.client.get(`${path}/${id}`);
922
+ }
923
+ catch (error) {
924
+ // A look that got no answer: the next one may.
925
+ if (!(error instanceof errors_1.NoAnswer))
926
+ throw error;
927
+ }
928
+ }
929
+ const done = await (0, change_1.send)(read, `${path}/${id}/finish`, {}, finishKey ?? key);
930
+ if (read.json) {
931
+ const publicUrl = publicPage(read, done.event?.slug);
932
+ out(publishJson(done, true, key, {
933
+ // The page guests see (added by the CLI, as `url` is).
934
+ ...(publicUrl ? { publicUrl } : {}),
935
+ ...(finishKey ? { finishIdempotencyKey: finishKey } : {}),
936
+ }));
937
+ return errors_1.EXIT.ok;
938
+ }
939
+ // The page guests see first; where it is managed on its own line.
940
+ const page = publicPage(read, done.event?.slug);
941
+ const link = linkOf(read, done.event?.path ? { path: done.event.path } : null) ??
942
+ linkOf(read, done.editor);
943
+ if (done.alreadyFinished) {
944
+ out('Already published.');
945
+ if (page)
946
+ out(`Public page: ${page}`);
947
+ }
948
+ else
949
+ out(`Published ${done.event?.title ?? title}${page ? `: ${page}` : '.'}`);
950
+ // The page is cached: a republish can look as if it didn't work.
951
+ if (page)
952
+ out('The public page can take a few minutes to show it.');
953
+ if (link)
954
+ out(`Manage it: ${link}`);
955
+ return errors_1.EXIT.ok;
956
+ }