uniweb 1.34.12 → 1.35.1

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,1690 @@
1
+ /**
2
+ * `uniweb promote` — a site's Promote, on the backend you are logged in to: getting it found,
3
+ * posts and ads on social networks and search engines, and what they brought.
4
+ *
5
+ * uniweb promote status [--json] the site's Promote on one screen, and what needs a person
6
+ * uniweb promote check <step> [--json] check one getting-found step (`sitemap`, say)
7
+ * uniweb promote connect <network> the address where a person connects an account
8
+ * uniweb promote post <file> make a post's draft, or update the one the file names
9
+ * uniweb promote campaign <file> the same for a campaign, its ad groups and ads
10
+ * uniweb promote show <id> [--json] one post or campaign, as a draft holds it
11
+ * uniweb promote delete <id> delete a post, a campaign, an ad group or an ad
12
+ * uniweb promote send <post> [--at <time> | --now] post it now, or at a time
13
+ * uniweb promote unschedule <post> a scheduled post a draft again, its time kept
14
+ * uniweb promote start | resume <campaign> [--yes] spend: say what, ask, then start
15
+ * uniweb promote pause <campaign> pause it wherever it runs
16
+ *
17
+ * The site is the one this project is synced to on that backend, or `--site <uuid>`. The
18
+ * workspace is `--org @x` or `--personal`, else the login's — as for every site request.
19
+ *
20
+ * ⭐ THE CLI IS A SECOND CLIENT OF THE SITE'S PROMOTE, BESIDE THE APP, AND KEEPS NO COPY OF IT.
21
+ * The backend holds the only one. Each command reads it fresh, and a write names the version of
22
+ * each item it read (`if_unmodified_since`), so a change made in the app since is refused, never
23
+ * written over. Nothing is synced, so there is nothing in the project to fall out of step.
24
+ *
25
+ * ⭐ AN ACCOUNT IS CONNECTED BY ITS PERSON, IN A BROWSER. `connect` hands over the network's
26
+ * consent page; the tokens it yields stay with the backend and never pass through the CLI.
27
+ *
28
+ * ⭐ AN AGENT SENDS AND SPENDS FOR ITS PERSON [Diego, 2026-11-16: "agents represent their users"].
29
+ * `start` and `resume` say what they will spend and ask at a terminal; `--yes` answers for an
30
+ * agent its person has agreed with, and without either they refuse rather than spend unseen.
31
+ *
32
+ * Auth: the session of the backend you are logged in to (`uniweb login`) / UNIWEB_TOKEN.
33
+ */
34
+
35
+ import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs'
36
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
37
+ import yaml from 'js-yaml'
38
+ import { mintUuidV7 } from '@uniweb/build/uwx'
39
+ import { BackendClient, WorkspaceMismatchError, describeWorkspace } from '../backend/client.js'
40
+ import { resolveWorkspace } from '../backend/workspace.js'
41
+ import {
42
+ YAML_READ,
43
+ campaignDeliveries,
44
+ connectionOf,
45
+ conversionNotes,
46
+ campaignOf,
47
+ campaignShape,
48
+ checkDraft,
49
+ REASONS,
50
+ reasonWords,
51
+ reviewWords,
52
+ deliveryOf,
53
+ fileWithFields,
54
+ fileWithIdentity,
55
+ findItem,
56
+ formatOf,
57
+ heldPictures,
58
+ idMatches,
59
+ indexPromotion,
60
+ isAddress,
61
+ kindOf,
62
+ pageRoute,
63
+ parseDraft,
64
+ picturesOf,
65
+ planCampaign,
66
+ planPost,
67
+ postMarkdown,
68
+ postShape,
69
+ resolvePage,
70
+ shapeYaml,
71
+ shortIds,
72
+ sitePages,
73
+ splitFrontmatter,
74
+ stateCounts,
75
+ versionOf,
76
+ viaResolver,
77
+ wentOut,
78
+ whyNot
79
+ } from '../backend/promote-drafts.js'
80
+ import { checkFlags } from '../utils/flag-guard.js'
81
+ import { confirm, isNonInteractive } from '../utils/interactive.js'
82
+ import { readSiteIdentity } from '../utils/site-identity.js'
83
+ import { projectSiteDir } from './site.js'
84
+
85
+ const c = {
86
+ reset: '\x1b[0m',
87
+ bold: '\x1b[1m',
88
+ dim: '\x1b[2m',
89
+ red: '\x1b[31m',
90
+ green: '\x1b[32m',
91
+ yellow: '\x1b[33m',
92
+ cyan: '\x1b[36m'
93
+ }
94
+ // As in every verb: errors on stderr, the rest on stdout — and under `--json` nothing but
95
+ // the JSON on stdout.
96
+ const say = {
97
+ ok: (m) => console.log(`${c.green}✓${c.reset} ${m}`),
98
+ info: (m) => console.log(`${c.cyan}→${c.reset} ${m}`),
99
+ warn: (m) => console.log(`${c.yellow}⚠${c.reset} ${m}`),
100
+ err: (m) => console.error(`${c.red}✗${c.reset} ${m}`),
101
+ dim: (m) => console.log(` ${c.dim}${m}${c.reset}`)
102
+ }
103
+
104
+ const USAGE = [
105
+ 'uniweb promote <command>',
106
+ ' status The site\'s Promote: getting found, networks, posts, campaigns,',
107
+ ' and what needs a person',
108
+ ' check <step> Check one getting-found step, e.g. uniweb promote check sitemap',
109
+ ' connect <network> The address where a person connects an account at a network',
110
+ ' post <file> Make a post\'s draft (Markdown, YAML or JSON), or update the one',
111
+ ' the file names; the file gets its id and version back',
112
+ ' campaign <file> The same for a campaign (YAML or JSON), its ad groups and ads',
113
+ ' show <id> One post or campaign, as a draft holds it',
114
+ ' delete <id> Delete a post, a campaign, an ad group or an ad',
115
+ ' send <post> Post it now, or at its send_at; --at <time> sets the time,',
116
+ ' --now sends it now whatever its time. Given its file, it writes',
117
+ ' the file first, so what goes out is what the file says',
118
+ ' unschedule <post> A scheduled post a draft again, its time kept',
119
+ ' start <campaign> Start it in its ad accounts — it says what it will spend and',
120
+ ' asks; --yes answers for you',
121
+ ' resume <campaign> Resume it where it was paused, the same way',
122
+ ' pause <campaign> Pause it wherever it runs',
123
+ '',
124
+ '--json gives any command\'s answer as JSON. An <id> is the one a command shows, a file',
125
+ 'a draft was written from, or a campaign\'s name.',
126
+ 'The site is the one this project is synced to, or --site <uuid>.',
127
+ 'The workspace is --org @x or --personal, else the one chosen at login.'
128
+ ].join('\n')
129
+
130
+ /** A site-content uuid, loosely: enough to tell one from anything else. */
131
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
132
+
133
+ /** Flags that take a value, so the value is not read as an argument. */
134
+ const VALUED = new Set(['--org', '--site', '--at'])
135
+
136
+ /** The arguments that are not flags, skipping the values of the flags that take one. */
137
+ function positionals(args) {
138
+ const out = []
139
+ for (let i = 0; i < args.length; i++) {
140
+ const a = args[i]
141
+ if (VALUED.has(a)) {
142
+ i++
143
+ continue
144
+ }
145
+ // A lone `-` is stdin, a value rather than a flag.
146
+ if (a.startsWith('-') && a !== '-') continue
147
+ out.push(a)
148
+ }
149
+ return out
150
+ }
151
+
152
+ /** The value of `--name <value>`, or undefined. */
153
+ function flagValue(args, name) {
154
+ const i = args.indexOf(name)
155
+ return i !== -1 ? args[i + 1] : undefined
156
+ }
157
+
158
+ /** A client on the backend you are logged in to, working in the command's workspace. */
159
+ async function open(args, command) {
160
+ const client = new BackendClient({ args, command })
161
+ const ws = await resolveWorkspace({ client, args })
162
+ if (ws.refused) return { refused: ws.reason }
163
+ client.setWorkspace(ws.workspace, { source: ws.source })
164
+ return { client, workspace: ws.workspace }
165
+ }
166
+
167
+ /**
168
+ * The site a command acts on: `--site <uuid>`, else this project's site on the backend the
169
+ * client goes to. Null, with the reason said, when there is neither.
170
+ */
171
+ async function targetSite(args, client, verb) {
172
+ const given = flagValue(args, '--site')
173
+ if (given !== undefined) {
174
+ if (!UUID.test(given || '')) {
175
+ say.err(`\`--site\` takes a site's uuid${given ? `, and \`${given}\` is not one` : ''}.`)
176
+ say.dim('`uniweb site list` shows each site with its uuid.')
177
+ return null
178
+ }
179
+ return given
180
+ }
181
+ const project = await projectSiteDir()
182
+ if (project.many) {
183
+ say.err(`This workspace has ${project.many.length} sites — run it inside one, or name it: uniweb promote ${verb} --site <uuid>`)
184
+ return null
185
+ }
186
+ const uuid = project.dir ? readSiteIdentity(project.dir, client.origin).uuid : null
187
+ if (!uuid) {
188
+ say.err(
189
+ project.dir
190
+ ? `This project has no site on ${client.origin} yet — push it first (uniweb push), or name one: uniweb promote ${verb} --site <uuid>`
191
+ : `No site named, and this is not a Uniweb project — name one: uniweb promote ${verb} --site <uuid>`
192
+ )
193
+ say.dim('`uniweb site list` shows each site with its uuid.')
194
+ return null
195
+ }
196
+ return uuid
197
+ }
198
+
199
+ /**
200
+ * What the backend said about a refused request, in words, and its own beside them.
201
+ *
202
+ * @param {Response} res
203
+ * @param {{ site: string, origin: string, what: string, index?: object }} ctx - `what` completes
204
+ * "You may not …"; `index` names a campaign a refusal names by uuid
205
+ */
206
+ async function sayRefusal(res, { site, origin, what, index = null, notFound = null }) {
207
+ const body = await res.clone().json().catch(() => null)
208
+ const reason = typeof body?.reason === 'string' ? body.reason : null
209
+ const own = [reason, body?.detail ?? body?.message ?? body?.title].filter((x) => typeof x === 'string' && x).join(': ')
210
+ if (res.status === 401) {
211
+ say.err(`Your session on ${origin} is not accepted — sign in again: uniweb login`)
212
+ } else if (res.status === 402) {
213
+ say.err(`${REASONS.feature_not_subscribed}.`)
214
+ } else if (res.status === 403 && body?.op === 'admin') {
215
+ say.err(`Only an admin of the site may ${what}. What is written stays, for one of them to do it.`)
216
+ } else if (res.status === 403 && body?.op === 'edit' && body?.target) {
217
+ say.err(`The account it goes out through is not shared with you for that. Use one you can use, or ask whoever connected it to share it.`)
218
+ } else if (res.status === 403) {
219
+ say.err(`You may not ${what} on this site${body?.op ? ` (it takes ${body.op})` : ''}.`)
220
+ } else if (res.status === 404) {
221
+ say.err(notFound ?? `${origin} has no site ${site}, or no longer has what was named — \`uniweb promote status\` shows what it has.`)
222
+ } else if (res.status === 409 && reason === 'campaign_started') {
223
+ const name = index?.byUuid.get(body?.campaign)?.data?.name
224
+ say.err(
225
+ `${name ? `“${name}”` : 'The campaign'} has started in an ad account, and what runs there is fixed, so the write is refused — nothing changed. ` +
226
+ 'Add an ad account to its `via`, or draft a new campaign.'
227
+ )
228
+ } else if (res.status === 409) {
229
+ say.err(`Refused, nothing changed: what was named changed since it was read — in the app, or by another run${own ? ` (${own})` : ''}. Read it again: uniweb promote show <id>`)
230
+ } else {
231
+ say.err(`The backend refused: HTTP ${res.status}${own ? ` — ${own}` : ''}`)
232
+ }
233
+ }
234
+
235
+ /** A 404 on reading a site's Promote: no such site there, or a backend without these routes. */
236
+ const notOffered = (origin, site) => `${origin} has no site ${site}, or does not offer Promote to this CLI yet.`
237
+
238
+ /**
239
+ * The networks the deployment offers to connect, as tokens. None when `/dev/config` names none,
240
+ * since the backend leaves `promote.networks` out while it offers none; null when `/dev/config`
241
+ * could not be read, so nothing is known.
242
+ */
243
+ async function offeredNetworks(client) {
244
+ const config = await client.discover().catch(() => null)
245
+ const list = config?.promote?.networks
246
+ if (!Array.isArray(list)) return config && typeof config === 'object' ? [] : null
247
+ return list.map((n) => (typeof n === 'string' ? n : n?.network ?? n?.token)).filter(Boolean)
248
+ }
249
+
250
+ // ── The promotion, read into the shape a person and an agent reason about ──────────────
251
+
252
+ /**
253
+ * The promotion's items, grouped: the site's networks, its getting-found steps with their
254
+ * readings, its posts with their parts and delivery, its campaigns with their deliveries, ad
255
+ * groups and ads. Backend's fields (a delivery, a reading, a campaign's tag) are read, never
256
+ * written.
257
+ *
258
+ * @param {{ uuid: string, items: object[] } | null} promotion
259
+ */
260
+ export function readView(promotion) {
261
+ const items = Array.isArray(promotion?.items) ? promotion.items : []
262
+ const bySection = (section) => items.filter((i) => i.section === section)
263
+ const childrenOf = (section, parent) => items.filter((i) => i.section === section && i.parent === parent)
264
+ const one = (section, parent) => childrenOf(section, parent)[0] ?? null
265
+
266
+ const networks = bySection('networks').map((i) => ({ uuid: i.uuid, updated_at: i.updated_at, ...i.data }))
267
+
268
+ const steps = bySection('getting_found').map((i) => {
269
+ const reading = one('getting_found/reading', i.uuid)
270
+ return {
271
+ uuid: i.uuid,
272
+ updated_at: i.updated_at,
273
+ step: i.data?.step ?? null,
274
+ skipped: i.data?.skipped === true,
275
+ reading: reading ? reading.data : null
276
+ }
277
+ })
278
+
279
+ const posts = bySection('posts').map((i) => {
280
+ const delivery = one('posts/delivery', i.uuid)
281
+ return {
282
+ uuid: i.uuid,
283
+ updated_at: i.updated_at,
284
+ ...i.data,
285
+ parts: childrenOf('posts/parts', i.uuid).map((p) => ({ uuid: p.uuid, ...p.data })),
286
+ delivery: delivery ? delivery.data : null,
287
+ state: delivery?.data?.status ?? 'draft'
288
+ }
289
+ })
290
+
291
+ const campaigns = bySection('campaigns').map((i) => {
292
+ const deliveries = childrenOf('campaigns/delivery', i.uuid).map((d) => d.data)
293
+ const adGroups = childrenOf('campaigns/ad_groups', i.uuid).map((g) => ({
294
+ uuid: g.uuid,
295
+ ...g.data,
296
+ ads: childrenOf('campaigns/ad_groups/ads', g.uuid).map((a) => {
297
+ const delivery = one('campaigns/ad_groups/ads/delivery', a.uuid)
298
+ return { uuid: a.uuid, ...a.data, delivery: delivery ? delivery.data : null }
299
+ })
300
+ }))
301
+ return {
302
+ uuid: i.uuid,
303
+ updated_at: i.updated_at,
304
+ ...i.data,
305
+ deliveries,
306
+ adGroups,
307
+ state: campaignState(deliveries),
308
+ started: deliveries.some((d) => d?.external_id)
309
+ }
310
+ })
311
+
312
+ return { uuid: promotion?.uuid ?? null, networks, steps, posts, campaigns }
313
+ }
314
+
315
+ /** One word for a campaign: `draft` until it runs anywhere, else what its deliveries say. */
316
+ function campaignState(deliveries) {
317
+ if (!deliveries.length) return 'draft'
318
+ const states = new Set(deliveries.map((d) => d?.status).filter(Boolean))
319
+ if (states.has('attention')) return 'attention'
320
+ if (states.has('active')) return 'active'
321
+ if (states.size === 1) return [...states][0]
322
+ return [...states].join(', ') || 'draft'
323
+ }
324
+
325
+ /** Spend rows summed per currency — `{ CAD: '16.00' }` — from the days the backend has read. */
326
+ export function sumSpend(rows) {
327
+ const out = {}
328
+ for (const r of Array.isArray(rows) ? rows : []) {
329
+ if (!r?.currency || r.amount == null) continue
330
+ const cents = Math.round(Number(r.amount) * 100)
331
+ if (!Number.isFinite(cents)) continue
332
+ out[r.currency] = (out[r.currency] ?? 0) + cents
333
+ }
334
+ return Object.fromEntries(Object.entries(out).map(([cur, cents]) => [cur, (cents / 100).toFixed(2)]))
335
+ }
336
+
337
+ // ── status ─────────────────────────────────────────────────────────────────────────
338
+
339
+ async function status(args) {
340
+ const json = args.includes('--json')
341
+ const conn = await open(args, 'Reading the site\'s Promote')
342
+ if (conn.refused) {
343
+ say.err(conn.refused)
344
+ return { exitCode: 2 }
345
+ }
346
+ const { client, workspace } = conn
347
+ const site = await targetSite(args, client, 'status')
348
+ if (!site) return { exitCode: 2 }
349
+
350
+ const [res, connectionsRes, offered] = await Promise.all([
351
+ client.readPromotion(site),
352
+ client.listConnections().catch(() => null),
353
+ offeredNetworks(client)
354
+ ])
355
+ if (!res.ok) {
356
+ await sayRefusal(res, { site, origin: client.origin, what: 'read Promote', notFound: notOffered(client.origin, site) })
357
+ return { exitCode: 1 }
358
+ }
359
+ const promotion = (await res.json().catch(() => null))?.promotion ?? null
360
+ const view = readView(promotion)
361
+ const connections = connectionsRes?.ok ? (await connectionsRes.json().catch(() => null))?.connections ?? [] : null
362
+ // Each post and campaign by the id the other commands take.
363
+ const ids = shortIds((promotion?.items ?? []).map((i) => i?.uuid))
364
+ for (const x of [...view.posts, ...view.campaigns]) x.short = ids.get(x.uuid)
365
+
366
+ // Spend, for the campaigns that run somewhere: what each network last reported.
367
+ for (const campaign of view.campaigns.filter((x) => x.started)) {
368
+ const spent = await client.campaignSpend(site, campaign.uuid).catch(() => null)
369
+ const rows = spent?.ok ? (await spent.json().catch(() => null))?.spend : null
370
+ campaign.spend = Array.isArray(rows) ? { total: sumSpend(rows), days: rows.length } : null
371
+ }
372
+
373
+ const needs = needsPerson(view, connections)
374
+ if (json) {
375
+ console.log(JSON.stringify({
376
+ backend: client.origin,
377
+ workspace: workspace ?? null,
378
+ site,
379
+ networksOffered: offered,
380
+ connections,
381
+ promotion: promotion ? view : null,
382
+ needsPerson: needs
383
+ }))
384
+ return { exitCode: 0 }
385
+ }
386
+
387
+ console.log(`${c.bold}Promote${c.reset} ${c.dim}— site ${site} in ${describeWorkspace(workspace)} on ${client.origin}${c.reset}`)
388
+ if (!promotion) {
389
+ say.info('This site has not used Promote yet: no networks, posts or campaigns.')
390
+ }
391
+ printSteps(view.steps)
392
+ printNetworks(view.networks, connections)
393
+ printPosts(view.posts)
394
+ printCampaigns(view.campaigns)
395
+ if (offered !== null) {
396
+ console.log(` ${c.dim}Can connect here:${c.reset} ${offered.length ? offered.join(', ') : 'no network yet, on this deployment'}`)
397
+ }
398
+ if (needs.length) {
399
+ console.log()
400
+ console.log(`${c.yellow}Ask the person first:${c.reset}`)
401
+ for (const n of needs) console.log(` • ${n.say}`)
402
+ }
403
+ return { exitCode: 0 }
404
+ }
405
+
406
+ /**
407
+ * The steps only a person can take, as status shows them: an account to reconnect or hand on,
408
+ * and the capability to turn on. A getting-found step is not among them by itself — which steps
409
+ * the backend can check is its own to say, so status shows each step's reading instead.
410
+ */
411
+ function needsPerson(view, connections) {
412
+ const needs = []
413
+ for (const k of Array.isArray(connections) ? connections : []) {
414
+ const state = k?.card?.state
415
+ if (state === 'needs_reconnect' || state === 'stopped') {
416
+ const who = k.card?.name || k.card?.handle || k.uuid
417
+ needs.push({
418
+ kind: 'connection',
419
+ connection: k.uuid,
420
+ state,
421
+ say: state === 'stopped'
422
+ ? `${k.card?.network ?? 'a'} connection “${who}” stopped: its person left; an admin of the workspace hands it on, in the app`
423
+ : `${k.card?.network ?? 'a'} connection “${who}” needs reconnecting, by its person, in the app`
424
+ })
425
+ }
426
+ }
427
+ for (const p of view.posts) {
428
+ if (p.state === 'failed' && p.delivery?.reason === 'promote_off') {
429
+ needs.push({ kind: 'capability', post: p.uuid, say: 'a scheduled post failed because the site has no Promote: it comes with the site\'s Analytics, turned on in the app' })
430
+ break
431
+ }
432
+ }
433
+ return needs
434
+ }
435
+
436
+ function printSteps(steps) {
437
+ if (!steps.length) {
438
+ console.log(` ${c.bold}Getting found${c.reset} ${c.dim}no step checked yet — uniweb promote check sitemap${c.reset}`)
439
+ return
440
+ }
441
+ steps.forEach((s, i) => {
442
+ const head = i === 0 ? `${c.bold}Getting found${c.reset} ` : ' '.repeat(15)
443
+ const r = s.reading
444
+ const what = s.skipped ? `${c.dim}skipped${c.reset}` : r ? `${r.state}${r.address ? ` — ${r.address}` : ''}${r.found && r.state !== 'done' ? ` (${foundWords(r.found)})` : ''}` : `${c.dim}not checked${c.reset}`
445
+ console.log(` ${head}${s.step}: ${what}`)
446
+ })
447
+ }
448
+
449
+ function printNetworks(networks, connections) {
450
+ if (!networks.length) {
451
+ console.log(` ${c.bold}Networks${c.reset} ${c.dim}none chosen yet${c.reset}`)
452
+ return
453
+ }
454
+ const byUuid = new Map((connections ?? []).map((k) => [k.uuid, k]))
455
+ networks.forEach((n, i) => {
456
+ const head = i === 0 ? `${c.bold}Networks${c.reset} ` : ' '.repeat(15)
457
+ const via = connectionOf(n.connection)
458
+ const k = byUuid.get(via.uuid)
459
+ const account = n.target?.name || via.name || k?.card?.name || via.handle || k?.card?.handle || 'no account chosen'
460
+ const known = k?.card?.state ?? via.state
461
+ const state = known && known !== 'connected' ? ` ${c.yellow}(${known})${c.reset}` : ''
462
+ console.log(` ${head}${n.use ?? '?'} through ${n.network ?? '?'}, “${account}”${state}`)
463
+ })
464
+ }
465
+
466
+ function printPosts(posts) {
467
+ const counts = new Map(stateCounts(posts.map((p) => p.state)))
468
+ const count = (state) => counts.get(state) ?? 0
469
+ const scheduled = posts
470
+ .filter((p) => p.state === 'scheduled')
471
+ .map((p) => p.send_at)
472
+ .filter(Boolean)
473
+ .sort()
474
+ const parts = [
475
+ `${count('draft')} draft${count('draft') === 1 ? '' : 's'}`,
476
+ `${count('scheduled')} scheduled${scheduled[0] ? ` (next ${scheduled[0]})` : ''}`,
477
+ `${count('published')} published`
478
+ ]
479
+ // Every other state the posts are in, counted: one in the network's review, and what didn't go out.
480
+ for (const [state, n] of counts) {
481
+ if (state === 'draft' || state === 'scheduled' || state === 'published') continue
482
+ parts.push(state === 'failed' || state === 'refused' ? `${c.red}${n} ${state}${c.reset}` : `${n} ${state}`)
483
+ }
484
+ console.log(` ${c.bold}Posts${c.reset} ${parts.join(' · ')}`)
485
+ // What can still be acted on, each by its id: a draft, a scheduled post, one that didn't go out.
486
+ for (const p of posts.filter((x) => x.state !== 'published' && x.state !== 'review')) {
487
+ const first = String(p.parts?.[0]?.text ?? '').replace(/\s+/g, ' ').trim()
488
+ const words = first ? `“${first.length > 40 ? `${first.slice(0, 39)}…` : first}”` : '(no words yet)'
489
+ const when = p.state === 'scheduled' && p.send_at ? ` ${p.send_at}` : ''
490
+ const why = (p.state === 'failed' || p.state === 'refused') && whyNot(p.delivery) ? ` — ${whyNot(p.delivery)}` : ''
491
+ console.log(`${' '.repeat(17)}${c.cyan}${p.short ?? p.uuid}${c.reset} ${p.state}${when} ${words}${why}`)
492
+ }
493
+ }
494
+
495
+ function printCampaigns(campaigns) {
496
+ if (!campaigns.length) {
497
+ console.log(` ${c.bold}Campaigns${c.reset} ${c.dim}none${c.reset}`)
498
+ return
499
+ }
500
+ campaigns.forEach((x, i) => {
501
+ const head = i === 0 ? `${c.bold}Campaigns${c.reset} ` : ' '.repeat(15)
502
+ const spent = x.spend?.total && Object.keys(x.spend.total).length
503
+ ? ` · spent ${Object.entries(x.spend.total).map(([cur, amt]) => `${amt} ${cur}`).join(' + ')}`
504
+ : ''
505
+ console.log(` ${head}${c.cyan}${x.short ?? x.uuid}${c.reset} ${x.name ?? x.uuid}: ${x.state}${spent}`)
506
+ })
507
+ }
508
+
509
+ /** A getting-found reading's code, in words; an unknown one is shown as it is. */
510
+ function foundWords(found) {
511
+ return {
512
+ sitemap_named: 'the site\'s robots.txt names its sitemap',
513
+ no_sitemap: 'the site\'s robots.txt names no sitemap',
514
+ no_robots: 'the site has no robots.txt',
515
+ site_unreachable: 'the live site did not answer',
516
+ no_address: 'the site has no live address yet — publish it first'
517
+ }[found] ?? found
518
+ }
519
+
520
+ // ── check ──────────────────────────────────────────────────────────────────────────
521
+
522
+ /**
523
+ * `uniweb promote check <step>` — check one getting-found step, and show its reading.
524
+ *
525
+ * ⭐ A STEP IS NAMED BY ITS TOKEN (`sitemap`), AND THE BACKEND KEEPS ONE ITEM FOR IT: the check
526
+ * finds the step's item, or makes it on its first check, so neither client makes one to check it,
527
+ * and a second is refused. A step the backend cannot check is `400`, with nothing made.
528
+ */
529
+ async function check(args) {
530
+ const json = args.includes('--json')
531
+ const step = positionals(args)[1]
532
+ if (!step) {
533
+ say.err('Name the step or the page: uniweb promote check sitemap, or uniweb promote check /holiday')
534
+ return { exitCode: 2 }
535
+ }
536
+ if (step.startsWith('/') || step.startsWith('page:/')) return checkLanding(args, step.replace(/^page:/, ''))
537
+ const at = await begin(args, 'Checking a getting-found step', `check ${step}`)
538
+ if (!at.client) return at
539
+ const { client, site } = at
540
+
541
+ const checked = await client.checkPromotionStep(site, step)
542
+ if (!checked.ok) {
543
+ if (checked.status === 400) {
544
+ say.err(`The backend cannot check \`${step}\` yet. The person does that step at the service, and marks it in the app.`)
545
+ return { exitCode: 1 }
546
+ }
547
+ await sayRefusal(checked, { site, origin: client.origin, what: 'check a step', notFound: notOffered(client.origin, site) })
548
+ return { exitCode: 1 }
549
+ }
550
+ const reading = (await checked.json().catch(() => null))?.reading ?? null
551
+ if (json) {
552
+ console.log(JSON.stringify({ backend: client.origin, site, step, reading }))
553
+ return { exitCode: 0 }
554
+ }
555
+ if (!reading) {
556
+ say.warn(`Checked \`${step}\`, and the backend answered no reading.`)
557
+ return { exitCode: 0 }
558
+ }
559
+ const words = foundWords(reading.found)
560
+ if (reading.state === 'done') {
561
+ say.ok(`${step}: done — ${words}${reading.address ? `: ${reading.address}` : ''}`)
562
+ } else {
563
+ say.warn(`${step}: ${reading.state} — ${words}`)
564
+ if (reading.detail) say.dim(reading.detail)
565
+ }
566
+ return { exitCode: 0 }
567
+ }
568
+
569
+ // ── a landing page: check <route> ──────────────────────────────────────────────────
570
+
571
+ /** The site's directory, when the site a command acts on is this project's; else null. */
572
+ async function siteFilesFor(site, origin) {
573
+ const project = await projectSiteDir().catch(() => null)
574
+ if (!project?.dir) return null
575
+ if (site && readSiteIdentity(project.dir, origin).uuid !== site) return null
576
+ return project.dir
577
+ }
578
+
579
+ function readSiteYml(dir) {
580
+ for (const name of ['site.yml', 'site.yaml']) {
581
+ const path = join(dir, name)
582
+ if (!existsSync(path)) continue
583
+ try {
584
+ return yaml.load(readFileSync(path, 'utf8'), YAML_READ) ?? null
585
+ } catch {
586
+ return null
587
+ }
588
+ }
589
+ return null
590
+ }
591
+
592
+ /**
593
+ * Notes on the pages a post or an ad lands on, from the site's files — each page's card, by
594
+ * doctor's rules for one page — and on what the site reports for a network to hear. Each is a
595
+ * note, never a gate: whoever sends or starts decides, with the notes in front of them.
596
+ *
597
+ * @param {string} dir - the site's directory
598
+ * @param {string[]} routes
599
+ * @param {{ networks?: string[]|null, goal?: string|null, quiet?: boolean }} [opts]
600
+ * @returns {Promise<{ issues: object[], notes: object[] }>}
601
+ */
602
+ async function landingNotes(dir, routes, { networks = null, goal = null, quiet = false } = {}) {
603
+ const { checkLinkPreviews } = await import('./doctor.js')
604
+ const issues = []
605
+ const consoleLog = console.log
606
+ if (quiet) console.log = () => {}
607
+ try {
608
+ for (const route of routes) {
609
+ const before = issues.length
610
+ if (!quiet) console.log(`${c.bold}${route}${c.reset}${c.dim}, as a landing page, from the site's files:${c.reset}`)
611
+ await checkLinkPreviews({ sitePath: dir, siteName: basename(dir), issues, route })
612
+ if (!quiet && issues.length === before) say.ok('its card has an image and a description')
613
+ }
614
+ } finally {
615
+ console.log = consoleLog
616
+ }
617
+ const notes = conversionNotes(readSiteYml(dir), { networks, goal })
618
+ if (!quiet) for (const n of notes) (n.ok ? say.ok : say.warn)(n.text)
619
+ return { issues, notes }
620
+ }
621
+
622
+ /**
623
+ * `uniweb promote check <route>` — a page as a landing page, from the site's files, on any site:
624
+ * one Uniweb hosts or a static one. Its card, by doctor's rules for one page, and what the site
625
+ * reports for a network to hear. It needs no backend.
626
+ */
627
+ async function checkLanding(args, route) {
628
+ const json = args.includes('--json')
629
+ const project = await projectSiteDir().catch(() => ({}))
630
+ if (project?.many) {
631
+ say.err(`This workspace has ${project.many.length} sites — run it inside the one the page is in.`)
632
+ return { exitCode: 2 }
633
+ }
634
+ if (!project?.dir) {
635
+ say.err('Run it in the site\'s project: a landing page is checked in its files.')
636
+ return { exitCode: 2 }
637
+ }
638
+ const found = await landingNotes(project.dir, [route], { goal: 'conversions', quiet: json })
639
+ const unknown = found.issues.some((i) => i.id === 'page-unknown')
640
+ if (json) console.log(JSON.stringify({ route, issues: found.issues, notes: found.notes }))
641
+ return { exitCode: unknown ? 1 : 0 }
642
+ }
643
+
644
+ // ── connect ────────────────────────────────────────────────────────────────────────
645
+
646
+ /**
647
+ * `uniweb promote connect <network>` — the address where a person connects an account.
648
+ *
649
+ * ⛔ THE CONSENT FINISHES ONLY IN A BROWSER SIGNED IN TO THE APP AS THE SAME PERSON. The backend
650
+ * answers a consent once, for whoever started it, within minutes; a browser signed in as anyone
651
+ * else, or not at all, spends it. So the command says that before the address, and an agent passes
652
+ * the address to its person rather than opening it somewhere they are not.
653
+ */
654
+ async function connectNetwork(args) {
655
+ const network = positionals(args)[1]
656
+ const conn = await open(args, 'Connecting an account')
657
+ if (conn.refused) {
658
+ say.err(conn.refused)
659
+ return { exitCode: 2 }
660
+ }
661
+ const { client } = conn
662
+ const offered = await offeredNetworks(client)
663
+ if (!network) {
664
+ say.err('Name the network: uniweb promote connect <network>')
665
+ if (offered?.length) say.dim(`${client.origin} can connect: ${offered.join(', ')}`)
666
+ return { exitCode: 2 }
667
+ }
668
+ if (offered && !offered.includes(network)) {
669
+ say.err(
670
+ offered.length
671
+ ? `${client.origin} cannot connect \`${network}\` — it offers ${offered.join(', ')}.`
672
+ : `${client.origin} cannot connect any network yet.`
673
+ )
674
+ return { exitCode: 2 }
675
+ }
676
+
677
+ const res = await client.startConnectionConsent({ network })
678
+ if (!res.ok) {
679
+ if (res.status === 404) {
680
+ say.err(`${client.origin} does not offer \`${network}\`.`)
681
+ } else {
682
+ await sayRefusal(res, { site: '', origin: client.origin, what: 'connect an account' })
683
+ }
684
+ return { exitCode: 1 }
685
+ }
686
+ const address = (await res.json().catch(() => null))?.address
687
+ if (!address) {
688
+ say.err('The backend started the consent but gave no address to open.')
689
+ return { exitCode: 1 }
690
+ }
691
+ say.info(`Connect ${network}, in a browser signed in to the app as you:`)
692
+ console.log(` ${address}`)
693
+ say.dim('The consent finishes only there, once, and only for whoever started it — open it soon.')
694
+ if (isNonInteractive(args)) {
695
+ say.dim('An agent hands this address to its person, who opens it.')
696
+ } else {
697
+ try {
698
+ const { openBrowser } = await import('../utils/registry-auth.js')
699
+ await openBrowser(address)
700
+ } catch {
701
+ /* the address is printed; opening it is a convenience */
702
+ }
703
+ }
704
+ return { exitCode: 0 }
705
+ }
706
+
707
+ // ── shared by the commands below ───────────────────────────────────────────────────
708
+
709
+ /** The client and the site a command acts on — or its exit code, the reason said. */
710
+ async function begin(args, command, verb) {
711
+ const conn = await open(args, command)
712
+ if (conn.refused) {
713
+ say.err(conn.refused)
714
+ return { exitCode: 2 }
715
+ }
716
+ const site = await targetSite(args, conn.client, verb)
717
+ if (!site) return { exitCode: 2 }
718
+ return { client: conn.client, workspace: conn.workspace, site }
719
+ }
720
+
721
+ /** The site's Promote, read fresh and indexed — or null, the refusal said. */
722
+ async function readIndex(client, site) {
723
+ const res = await client.readPromotion(site)
724
+ if (!res.ok) {
725
+ await sayRefusal(res, { site, origin: client.origin, what: 'read Promote', notFound: notOffered(client.origin, site) })
726
+ return null
727
+ }
728
+ return indexPromotion((await res.json().catch(() => null))?.promotion ?? null)
729
+ }
730
+
731
+ /** The site's pages as pushed — null when it has none there, or they could not be read. */
732
+ async function readPages(client, site) {
733
+ try {
734
+ const res = await client.pullSiteContent(site)
735
+ if (!res?.ok) return null
736
+ const { entityDocFromUwx } = await import('../backend/site-sync.js')
737
+ const doc = entityDocFromUwx(Buffer.from(await res.arrayBuffer()))
738
+ return doc ? sitePages(doc) : null
739
+ } catch {
740
+ return null
741
+ }
742
+ }
743
+
744
+ /** The caller's connections — null when they could not be listed. */
745
+ async function listedConnections(client) {
746
+ const res = await client.listConnections().catch(() => null)
747
+ return res?.ok ? ((await res.json().catch(() => null))?.connections ?? []) : null
748
+ }
749
+
750
+ /** An item's name in a line: a post's first words, a campaign's or an ad group's name, an ad's headline. */
751
+ function labelOf(index, item) {
752
+ const words = (text) => {
753
+ const t = String(text ?? '').replace(/\s+/g, ' ').trim()
754
+ return t.length > 48 ? `${t.slice(0, 47)}…` : t
755
+ }
756
+ if (item.section === 'posts') {
757
+ const first = index.children('posts/parts', item.uuid)[0]?.data?.text
758
+ return first ? `“${words(first)}”` : '(no words yet)'
759
+ }
760
+ if (item.section === 'campaigns/ad_groups/ads') {
761
+ const headline = item.data?.headlines?.[0] ?? index.children('campaigns/ad_groups/ads/parts', item.uuid)[0]?.data?.text
762
+ return headline ? `“${words(headline)}”` : '(no words yet)'
763
+ }
764
+ return item.data?.name ? `“${item.data.name}”` : '(no name)'
765
+ }
766
+
767
+ /** A `networks` item as a person reads it: `facebook “Maple Bakery Ads”`. */
768
+ function accountName(index, uuid, connections) {
769
+ const n = index.byUuid.get(uuid)
770
+ if (!n) return `account ${uuid}`
771
+ const via = connectionOf(n.data?.connection)
772
+ const k = (connections ?? []).find((c) => c.uuid === via.uuid)
773
+ const name = n.data?.target?.name || via.name || k?.card?.name || via.handle || k?.card?.handle
774
+ return `${n.data?.network ?? '?'}${name ? ` “${name}”` : ''}`
775
+ }
776
+
777
+ /** The file a command names, when it names one: its path, text and format. */
778
+ function draftFile(arg) {
779
+ const path = resolve(arg)
780
+ if (!existsSync(path) || !statSync(path).isFile()) return null
781
+ const text = readFileSync(path, 'utf8')
782
+ return { path, text, format: formatOf(path, text) }
783
+ }
784
+
785
+ /** The id in a file a draft was written from, else null. */
786
+ function idInFile(text, format) {
787
+ try {
788
+ if (format === 'json') return JSON.parse(text)?.id ?? null
789
+ const src = format === 'markdown' ? splitFrontmatter(text).front : text
790
+ const obj = src ? yaml.load(src, YAML_READ) : null
791
+ return typeof obj?.id === 'string' ? obj.id : null
792
+ } catch {
793
+ return null
794
+ }
795
+ }
796
+
797
+ /**
798
+ * The item a command names — by the id a command shows, a campaign's name, or the file a draft
799
+ * was written from — or null, with what it matched said.
800
+ */
801
+ function pick(index, arg, kinds) {
802
+ let ref = arg
803
+ const path = resolve(arg)
804
+ if (existsSync(path) && statSync(path).isFile()) {
805
+ const text = readFileSync(path, 'utf8')
806
+ ref = idInFile(text, formatOf(path, text))
807
+ if (!ref) {
808
+ say.err(`${arg} holds no id yet — write it first: uniweb promote ${kinds.includes('post') ? 'post' : 'campaign'} ${arg}`)
809
+ return null
810
+ }
811
+ }
812
+ const found = findItem(index, ref, { kinds })
813
+ if (found.item) return found.item
814
+ const ids = shortIds(index.items.map((i) => i.uuid))
815
+ if (found.many) {
816
+ say.err(`\`${ref}\` names ${found.many.length} things — give more of its id:`)
817
+ for (const i of found.many) say.dim(`${ids.get(i.uuid)} ${kindOf(i)} ${labelOf(index, i)}`)
818
+ return null
819
+ }
820
+ say.err(`This site's Promote has no ${kinds.join(' or ')} \`${ref}\` — \`uniweb promote status\` lists what it has.`)
821
+ return null
822
+ }
823
+
824
+ /** Whether `--at`'s value is a time with its offset, as the backend takes one. */
825
+ function isTime(value) {
826
+ return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})$/.test(value) && !Number.isNaN(Date.parse(value))
827
+ }
828
+
829
+ const sameInstant = (a, b) => typeof a === 'string' && typeof b === 'string' && Date.parse(a) === Date.parse(b)
830
+
831
+ /** An amount as money reads: `10.00` for the `10` YAML reads `10.00` as; a string as written. */
832
+ const money = (v) => (typeof v === 'number' && Number.isFinite(v) ? v.toFixed(2) : String(v))
833
+
834
+ /** Whether a value is an amount of money: a number, or the decimal text of one. */
835
+ const isAmount = (v) => v !== null && v !== undefined && v !== '' && Number.isFinite(Number(v))
836
+
837
+ /** Amounts summed in cents, kept as the decimal text a network reads: `15.00`; null when none is given. */
838
+ function sumAmounts(values) {
839
+ let cents = 0
840
+ let any = false
841
+ for (const v of values) {
842
+ const n = Math.round(Number(v) * 100)
843
+ if (v === null || v === undefined || v === '' || !Number.isFinite(n)) continue
844
+ cents += n
845
+ any = true
846
+ }
847
+ return any ? (cents / 100).toFixed(2) : null
848
+ }
849
+
850
+ // ── drafts: post, campaign, show, delete ───────────────────────────────────────────
851
+
852
+ /** A draft's text, from the file a command names or from stdin for `-`. */
853
+ function readInput(args, kind) {
854
+ const file = positionals(args)[1]
855
+ if (!file) return { error: `Name the draft: uniweb promote ${kind} <file>, or - to read it from stdin` }
856
+ if (file === '-') {
857
+ try {
858
+ return { file: null, shown: 'stdin', text: readFileSync(0, 'utf8'), dir: process.cwd() }
859
+ } catch (err) {
860
+ return { error: `Could not read stdin: ${err.message}` }
861
+ }
862
+ }
863
+ const path = resolve(file)
864
+ if (!existsSync(path) || !statSync(path).isFile()) return { error: `No file ${file}.` }
865
+ return { file: path, shown: file, text: readFileSync(path, 'utf8'), dir: dirname(path) }
866
+ }
867
+
868
+ /**
869
+ * A draft in the backend's terms: `via` as the site's `networks` item (made in the same write
870
+ * where the site has none for that network), `page` as the page's item, an ad's account one of its
871
+ * campaign's. Pictures stay as written until they are uploaded.
872
+ */
873
+ function translateDraft(draft, { index, pages, connections }) {
874
+ const errors = []
875
+ const out = structuredClone(draft)
876
+ const via = viaResolver({ networks: index.top('networks'), connections, mint: mintUuidV7 })
877
+ const page = (raw, where) => {
878
+ if (raw && !pages) {
879
+ errors.push(`${where} links to a page, and the site has no content pushed here yet — push it first (uniweb push).`)
880
+ return undefined
881
+ }
882
+ const r = resolvePage(raw, pages, where)
883
+ if (r.error) errors.push(r.error)
884
+ return r.error ? undefined : r.uuid
885
+ }
886
+
887
+ if (draft.kind === 'post') {
888
+ if (draft.fields.via !== undefined || !draft.id) {
889
+ const r = via.resolve(draft.fields.via, 'posts', 'The post')
890
+ if (r.error) errors.push(r.error)
891
+ else out.fields.via = r.uuid
892
+ }
893
+ if (draft.fields.page !== undefined) out.fields.page = page(draft.fields.page, 'The post')
894
+ return { draft: out, creates: via.creates(), errors }
895
+ }
896
+
897
+ let campaignVia
898
+ if (draft.fields.via !== undefined) {
899
+ const list = draft.fields.via === null ? [] : Array.isArray(draft.fields.via) ? draft.fields.via : [draft.fields.via]
900
+ const uuids = []
901
+ list.forEach((raw, i) => {
902
+ const r = via.resolve(raw, 'ads', list.length > 1 ? `The campaign's account ${i + 1}` : 'The campaign')
903
+ if (r.error) errors.push(r.error)
904
+ else uuids.push(r.uuid)
905
+ })
906
+ out.fields.via = [...new Set(uuids)]
907
+ campaignVia = out.fields.via
908
+ } else {
909
+ const stored = draft.id ? index.byUuid.get(draft.id) : null
910
+ campaignVia = Array.isArray(stored?.data?.via) ? stored.data.via : []
911
+ }
912
+ const made = () => via.creates()
913
+ const accounts = campaignVia.map((u) => index.byUuid.get(u) ?? made().find((op) => op.uuid === u) ?? { uuid: u, data: {} })
914
+
915
+ for (const [i, g] of (draft.adGroups ?? []).entries()) {
916
+ for (const [j, a] of (g.ads ?? []).entries()) {
917
+ const where = `Ad ${j + 1} of ad group ${i + 1}`
918
+ const ad = out.adGroups[i].ads[j]
919
+ if (a.fields.via !== undefined && a.fields.via !== null) {
920
+ const raw = a.fields.via
921
+ const want = typeof raw === 'object' ? raw : { network: raw }
922
+ // A stored account's connection reads back as an entity reference, one made in this write as its uuid.
923
+ const matches = accounts.filter((n) =>
924
+ typeof raw === 'string' && idMatches(n.uuid, raw)
925
+ ? true
926
+ : n.data?.network === want.network && (!want.connection || idMatches(connectionOf(n.data?.connection).uuid, String(want.connection)))
927
+ )
928
+ if (matches.length === 1) ad.fields.via = matches[0].uuid
929
+ else if (!matches.length) errors.push(`${where} goes through ${typeof raw === 'string' ? raw : want.network}, and the campaign does not run there — add it to the campaign's \`via\`.`)
930
+ else errors.push(`${where}: the campaign runs in ${matches.length} ${want.network} accounts — name the ad's by its id.`)
931
+ } else if (!a.id) {
932
+ if (accounts.length === 1) ad.fields.via = accounts[0].uuid
933
+ else if (accounts.length > 1) errors.push(`${where}: the campaign runs in ${accounts.length} ad accounts — name the one the ad runs in, \`via:\`.`)
934
+ }
935
+ if (a.fields.page !== undefined) ad.fields.page = page(a.fields.page, where)
936
+ }
937
+ }
938
+ return { draft: out, creates: via.creates(), errors }
939
+ }
940
+
941
+ /**
942
+ * Upload the pictures a draft names as files, each as one of the site's own and kept in its
943
+ * format, as the app uploads a post's picture. An address is kept as written: an `https:` one, or
944
+ * one the site's Promote holds already, as a read gives it back (`held`).
945
+ *
946
+ * @param {Set<string>} held - `heldPictures` of the promotion as read
947
+ * @returns {Promise<{ map: Map<string,string> } | { error: string }>} picture as written → its address
948
+ */
949
+ async function uploadPictures(client, site, pictures, dir, held) {
950
+ const map = new Map()
951
+ const located = []
952
+ const used = new Set()
953
+ for (const p of pictures) {
954
+ if (isAddress(p) || held.has(p)) continue
955
+ const path = isAbsolute(p) ? p : resolve(dir, p)
956
+ if (!existsSync(path) || !statSync(path).isFile()) {
957
+ return {
958
+ error: path === p
959
+ ? `No picture ${p}: there is no such file, and the site's Promote holds no picture at that address. A picture is a file, or an address starting https://.`
960
+ : `No picture ${p} (looked for ${path}).`
961
+ }
962
+ }
963
+ // The name the upload is planned under: the file's own, never where it sits on this machine.
964
+ let name = basename(path)
965
+ for (let n = 2; used.has(name); n++) name = `${n}-${basename(path)}`
966
+ used.add(name)
967
+ located.push({ picture: p, ref: `/promote/${name}`, path })
968
+ }
969
+ if (!located.length) return { map }
970
+ const { uploadSiteMedia, describeAssetRefusal } = await import('../backend/site-media.js')
971
+ const refs = located.map(({ ref, path }) => ({ ref, path }))
972
+ const keepFormat = new Set(located.map((l) => l.ref))
973
+ let result
974
+ try {
975
+ // Charged to the site, which this command read: its owner exists before the bytes do.
976
+ result = await uploadSiteMedia(client, process.cwd(), refs, { siteUuid: site, keepFormat, warn: (m) => say.warn(m) })
977
+ } catch (err) {
978
+ const lines = describeAssetRefusal?.(err)
979
+ return { error: Array.isArray(lines) && lines.length ? lines.join('\n') : `The pictures could not be uploaded: ${err.message}` }
980
+ }
981
+ for (const l of located) {
982
+ const address = result.map?.[l.ref]
983
+ if (!address) return { error: `The picture ${l.picture} could not be uploaded${result.failed?.length ? ` (HTTP ${result.failed[0].status})` : ''}.` }
984
+ map.set(l.picture, address)
985
+ }
986
+ return { map }
987
+ }
988
+
989
+ /** Each picture as written replaced by its address. */
990
+ function withPictures(draft, map) {
991
+ const swap = (parts) => {
992
+ for (const p of parts ?? []) p.pictures = p.pictures.map((x) => map.get(x) ?? x)
993
+ }
994
+ swap(draft.parts)
995
+ for (const g of draft.adGroups ?? []) for (const a of g.ads ?? []) swap(a.parts)
996
+ }
997
+
998
+ /** The index after a write, from the write's own answer, for when it cannot be read again. */
999
+ function indexAfterWrite(index, ops, results) {
1000
+ const items = new Map(index.items.map((i) => [i.uuid, { ...i }]))
1001
+ ops.forEach((op, n) => {
1002
+ const at = results?.[n]?.updated_at ?? null
1003
+ if (op.kind === 'delete') items.delete(op.uuid)
1004
+ else if (op.kind === 'update') items.set(op.uuid, { ...items.get(op.uuid), data: op.data, updated_at: at })
1005
+ else items.set(op.uuid, { uuid: op.uuid, section: op.section, ...(op.parent ? { parent: op.parent } : {}), data: op.data, updated_at: at })
1006
+ })
1007
+ return indexPromotion({ uuid: index.uuid, items: [...items.values()] })
1008
+ }
1009
+
1010
+ /**
1011
+ * Write a draft as `post` and `campaign` write one: checked against the promotion as read, its
1012
+ * names put in the backend's terms, its pictures uploaded, then written in one batch, and the
1013
+ * file it came from given its ids and versions. `send` writes a file this way before it sends it,
1014
+ * so what goes out is what the file says.
1015
+ *
1016
+ * @returns {Promise<object>} what the write left — `after`, the promotion once written — or
1017
+ * `{ exitCode }` once it has said why nothing was written
1018
+ */
1019
+ async function writeParsed({ client, site, index, input, format, draft, kind }) {
1020
+ const problems = checkDraft(index, draft)
1021
+ if (problems.length) {
1022
+ for (const p of problems) say.err(p)
1023
+ return { exitCode: 1 }
1024
+ }
1025
+
1026
+ const [pages, connections] = await Promise.all([readPages(client, site), listedConnections(client)])
1027
+ const translated = translateDraft(draft, { index, pages, connections })
1028
+ if (translated.errors.length) {
1029
+ for (const e of translated.errors) say.err(e)
1030
+ return { exitCode: 2 }
1031
+ }
1032
+ const pictures = await uploadPictures(client, site, picturesOf(draft), input.dir, heldPictures(index))
1033
+ if (pictures.error) {
1034
+ say.err(pictures.error)
1035
+ return { exitCode: 1 }
1036
+ }
1037
+ withPictures(translated.draft, pictures.map)
1038
+
1039
+ const plan = (kind === 'post' ? planPost : planCampaign)(index, translated.draft, { mint: mintUuidV7, language: pages?.language })
1040
+ const ops = [...translated.creates, ...plan.ops]
1041
+ const wasScheduled = kind === 'post' && deliveryOf(index, index.byUuid.get(plan.uuid))?.status === 'scheduled'
1042
+
1043
+ let after = index
1044
+ if (ops.length) {
1045
+ const res = await client.writePromotionItems(site, ops)
1046
+ if (!res.ok) {
1047
+ await sayRefusal(res, { site, origin: client.origin, what: `write this site's ${kind}s`, index })
1048
+ return { exitCode: 1 }
1049
+ }
1050
+ const written = await res.json().catch(() => null)
1051
+ after = (await readIndex(client, site).catch(() => null)) ?? indexAfterWrite(index, ops, written?.results)
1052
+ }
1053
+
1054
+ // The file keeps what it was written at, so the next run updates the same draft.
1055
+ const version = (uuid) => {
1056
+ const item = after.byUuid.get(uuid)
1057
+ return item ? versionOf(after, item) : null
1058
+ }
1059
+ let fileNote = null
1060
+ if (input.file) {
1061
+ const next = fileWithIdentity(input.text, { format, kind }, { uuid: plan.uuid, groups: plan.groups }, version)
1062
+ if (!next) fileNote = `Could not write the ids into ${input.shown} — its next run would make another draft. Add \`id: ${plan.uuid}\` and \`version: ${version(plan.uuid)}\` to it.`
1063
+ else if (next.text !== readFileSync(input.file, 'utf8')) {
1064
+ writeFileSync(input.file, next.text)
1065
+ if (next.whole) fileNote = `Wrote ${input.shown} again whole, with its ids: its layout could not be kept.`
1066
+ }
1067
+ }
1068
+ return { after, plan, ops, pages, connections, wasScheduled, version, fileNote }
1069
+ }
1070
+
1071
+ /**
1072
+ * `uniweb promote post <file>` and `campaign <file>` — make a draft, or update the one the file
1073
+ * names, and write its ids and versions back into the file.
1074
+ */
1075
+ async function writeDraft(args, kind) {
1076
+ const json = args.includes('--json')
1077
+ const input = readInput(args, kind)
1078
+ if (input.error) {
1079
+ say.err(input.error)
1080
+ return { exitCode: 2 }
1081
+ }
1082
+ const format = formatOf(input.file, input.text)
1083
+ const parsed = parseDraft(input.text, { format, kind })
1084
+ if (parsed.error) {
1085
+ say.err(parsed.error)
1086
+ return { exitCode: 2 }
1087
+ }
1088
+ const draft = parsed.draft
1089
+
1090
+ const at = await begin(args, kind === 'post' ? 'Writing a post' : 'Writing a campaign', kind)
1091
+ if (!at.client) return at
1092
+ const { client, site } = at
1093
+ const index = await readIndex(client, site)
1094
+ if (!index) return { exitCode: 1 }
1095
+ const wrote = await writeParsed({ client, site, index, input, format, draft, kind })
1096
+ if (!wrote.after) return wrote
1097
+ const { after, plan, ops, pages, connections, wasScheduled, version, fileNote } = wrote
1098
+
1099
+ const ids = shortIds(after.items.map((i) => i.uuid))
1100
+ const item = after.byUuid.get(plan.uuid)
1101
+ const id = ids.get(plan.uuid) ?? plan.uuid
1102
+ if (json) {
1103
+ console.log(JSON.stringify({
1104
+ backend: client.origin,
1105
+ site,
1106
+ kind,
1107
+ id: plan.uuid,
1108
+ short: id,
1109
+ version: version(plan.uuid),
1110
+ made: !draft.id,
1111
+ writes: ops.length,
1112
+ file: input.file ? input.shown : null,
1113
+ kept: (plan.kept ?? []).map((k) => ({ ...k, short: ids.get(k.uuid) }))
1114
+ }))
1115
+ return { exitCode: 0 }
1116
+ }
1117
+
1118
+ if (!ops.length) {
1119
+ say.ok(`Nothing to change: ${kind} ${id} already says what ${input.shown} says.`)
1120
+ } else if (kind === 'post') {
1121
+ const via = after.byUuid.get(item?.data?.via)
1122
+ const route = pageRoute(item?.data?.page, pages)
1123
+ say.ok(
1124
+ `${draft.id ? 'Updated' : 'Drafted'} post ${id}${via ? ` on ${via.data?.network}` : ''}` +
1125
+ `${route ? `, linking to ${route}` : ', linking to no page'}${item?.data?.language ? ` (${item.data.language})` : ''}.`
1126
+ )
1127
+ if (wasScheduled && deliveryOf(after, item)?.status !== 'scheduled') {
1128
+ say.warn(`It was scheduled, and a change makes it a draft again, its time kept: uniweb promote send ${id} schedules it again.`)
1129
+ }
1130
+ } else {
1131
+ const groups = after.children('campaigns/ad_groups', plan.uuid)
1132
+ const ads = groups.flatMap((g) => after.children('campaigns/ad_groups/ads', g.uuid))
1133
+ const accounts = (Array.isArray(item?.data?.via) ? item.data.via : []).map((u) => accountName(after, u, connections))
1134
+ say.ok(
1135
+ `${draft.id ? 'Updated' : 'Drafted'} campaign ${labelOf(after, item)} (${id}): ${groups.length} ad group${groups.length === 1 ? '' : 's'}, ` +
1136
+ `${ads.length} ad${ads.length === 1 ? '' : 's'}, ${accounts.length ? `in ${accounts.join(', ')}` : 'in no ad account yet'}.`
1137
+ )
1138
+ for (const k of plan.kept) {
1139
+ say.info(`Kept, not in your file: ${k.kind} ${k.name ? `“${k.name}” ` : ''}(${ids.get(k.uuid)}). \`uniweb promote delete ${ids.get(k.uuid)}\` deletes it.`)
1140
+ }
1141
+ }
1142
+ if (fileNote) say.warn(fileNote)
1143
+ else if (!input.file && ops.length) say.dim(`From stdin, so no file keeps its ids: give your next draft of it \`id: ${plan.uuid}\` and \`version: ${version(plan.uuid)}\`.`)
1144
+ // The pages it lands on, checked in the site's files where this project holds them.
1145
+ const landing = landingOf(after, item, pages)
1146
+ const dir = landing.routes.length ? await siteFilesFor(site, client.origin) : null
1147
+ if (dir) {
1148
+ console.log()
1149
+ await landingNotes(dir, landing.routes, { networks: landing.networks, goal: landing.goal })
1150
+ }
1151
+ if (kind === 'post' && wentOut(deliveryOf(after, item)) === false) {
1152
+ const sendAt = item?.data?.send_at
1153
+ if (deliveryOf(after, item)?.status === 'scheduled') say.dim(`Scheduled for ${sendAt}: \`uniweb promote unschedule ${id}\` makes it a draft again`)
1154
+ else say.dim(sendAt ? `Send it at its time, ${sendAt}: uniweb promote send ${id}` : `Send it: uniweb promote send ${id} [--at <time>]`)
1155
+ } else if (kind === 'campaign') {
1156
+ say.dim(`Start it: uniweb promote start ${id} — it says what it will spend, and asks first`)
1157
+ }
1158
+ return { exitCode: 0 }
1159
+ }
1160
+
1161
+ /** The routes a post or a campaign lands on, the networks it goes out on, and a campaign's goal. */
1162
+ function landingOf(index, item, pages) {
1163
+ if (!item) return { routes: [], networks: [], goal: null }
1164
+ const networkOf = (uuid) => index.byUuid.get(uuid)?.data?.network
1165
+ if (item.section === 'posts') {
1166
+ const route = pages?.byUuid.get(item.data?.page)?.route
1167
+ return { routes: route ? [route] : [], networks: [networkOf(item.data?.via)].filter(Boolean), goal: null }
1168
+ }
1169
+ const ads = index.children('campaigns/ad_groups', item.uuid).flatMap((g) => index.children('campaigns/ad_groups/ads', g.uuid))
1170
+ const routes = [...new Set(ads.map((a) => pages?.byUuid.get(a.data?.page)?.route).filter(Boolean))]
1171
+ const via = Array.isArray(item.data?.via) ? item.data.via : []
1172
+ return { routes, networks: [...new Set(via.map(networkOf).filter(Boolean))], goal: item.data?.goal ?? null }
1173
+ }
1174
+
1175
+ /** What a post or a campaign is doing, in lines: its state, and each delivery's. */
1176
+ function stateLines(index, target, connections) {
1177
+ const ids = shortIds(index.items.map((i) => i.uuid))
1178
+ const lines = []
1179
+ if (target.section === 'posts') {
1180
+ const d = deliveryOf(index, target)
1181
+ const state = d?.status ?? 'draft'
1182
+ lines.push(`Post ${ids.get(target.uuid)}: ${state}${d?.status === 'scheduled' && target.data?.send_at ? ` for ${target.data.send_at}` : ''}${d?.sent_at ? ` at ${d.sent_at}` : ''}`)
1183
+ if (d?.network_url) lines.push(` on the network: ${d.network_url}`)
1184
+ if (d?.link) lines.push(` it links to: ${d.link}`)
1185
+ if (d?.reason) lines.push(` ${reasonWords(d.reason)}${d.detail ? ` — ${d.detail}` : ''}`)
1186
+ return lines
1187
+ }
1188
+ const deliveries = campaignDeliveries(index, target)
1189
+ const state = deliveries.length ? [...new Set(deliveries.map((d) => d.status))].join(', ') : 'draft'
1190
+ lines.push(`Campaign ${ids.get(target.uuid)} ${labelOf(index, target)}: ${state}${target.data?.tag ? ` (tag ${target.data.tag})` : ''}`)
1191
+ for (const d of deliveries) {
1192
+ lines.push(` ${accountName(index, d.via, connections)}: ${d.status}${d.review ? `, the network's review: ${reviewWords(d.review)}` : ''}${d.currency ? `, in ${d.currency}` : ''}${d.reason ? ` — ${reasonWords(d.reason)}` : ''}${d.detail ? ` (${d.detail})` : ''}`)
1193
+ }
1194
+ for (const g of index.children('campaigns/ad_groups', target.uuid)) {
1195
+ for (const a of index.children('campaigns/ad_groups/ads', g.uuid)) {
1196
+ const d = deliveryOf(index, a)
1197
+ if (d) lines.push(` ad ${ids.get(a.uuid)} ${labelOf(index, a)}: ${d.status}${d.reason ? ` — ${reasonWords(d.reason)}` : ''}${d.network_url ? ` ${d.network_url}` : ''}`)
1198
+ }
1199
+ }
1200
+ return lines
1201
+ }
1202
+
1203
+ /**
1204
+ * `uniweb promote show <id>` — one post or campaign as a draft holds it, so it round-trips: a
1205
+ * post as Markdown, a campaign as YAML. What it is doing goes to stderr, so `show <id> > file`
1206
+ * keeps the draft alone.
1207
+ */
1208
+ async function show(args) {
1209
+ const json = args.includes('--json')
1210
+ const arg = positionals(args)[1]
1211
+ if (!arg) {
1212
+ say.err('Name it: uniweb promote show <id>')
1213
+ return { exitCode: 2 }
1214
+ }
1215
+ const at = await begin(args, 'Reading the site\'s Promote', `show ${arg}`)
1216
+ if (!at.client) return at
1217
+ const { client, site } = at
1218
+ const index = await readIndex(client, site)
1219
+ if (!index) return { exitCode: 1 }
1220
+ const item = pick(index, arg, ['post', 'campaign', 'ad group', 'ad'])
1221
+ if (!item) return { exitCode: 2 }
1222
+ const target = item.section === 'posts' ? item : campaignOf(index, item)
1223
+ const [pages, connections] = await Promise.all([readPages(client, site), listedConnections(client)])
1224
+ const shape = target.section === 'posts' ? postShape(index, target, pages) : campaignShape(index, target, pages)
1225
+ if (json) {
1226
+ const ids = shortIds(index.items.map((i) => i.uuid))
1227
+ console.log(JSON.stringify({
1228
+ backend: client.origin,
1229
+ site,
1230
+ kind: kindOf(target),
1231
+ short: ids.get(target.uuid),
1232
+ draft: shape,
1233
+ ...(target.section === 'posts'
1234
+ ? { delivery: deliveryOf(index, target) }
1235
+ : {
1236
+ tag: target.data?.tag ?? null,
1237
+ deliveries: campaignDeliveries(index, target),
1238
+ ads: index.children('campaigns/ad_groups', target.uuid).flatMap((g) =>
1239
+ index.children('campaigns/ad_groups/ads', g.uuid).map((a) => ({ id: a.uuid, short: ids.get(a.uuid), delivery: deliveryOf(index, a) }))
1240
+ )
1241
+ })
1242
+ }))
1243
+ return { exitCode: 0 }
1244
+ }
1245
+ for (const line of stateLines(index, target, connections)) console.error(`${c.dim}${line}${c.reset}`)
1246
+ const text = target.section === 'posts' ? (postMarkdown(shape) ?? shapeYaml(shape)) : shapeYaml(shape)
1247
+ console.log(text.replace(/\n$/, ''))
1248
+ return { exitCode: 0 }
1249
+ }
1250
+
1251
+ /** `uniweb promote delete <id>` — a post, a campaign, an ad group or an ad. */
1252
+ async function deleteItem(args) {
1253
+ const json = args.includes('--json')
1254
+ const arg = positionals(args)[1]
1255
+ if (!arg) {
1256
+ say.err('Name it: uniweb promote delete <id>')
1257
+ return { exitCode: 2 }
1258
+ }
1259
+ const at = await begin(args, 'Deleting a draft', `delete ${arg}`)
1260
+ if (!at.client) return at
1261
+ const { client, site } = at
1262
+ const index = await readIndex(client, site)
1263
+ if (!index) return { exitCode: 1 }
1264
+ const item = pick(index, arg, ['post', 'campaign', 'ad group', 'ad'])
1265
+ if (!item) return { exitCode: 2 }
1266
+ const ids = shortIds(index.items.map((i) => i.uuid))
1267
+ const what = `${kindOf(item)} ${labelOf(index, item)} (${ids.get(item.uuid)})`
1268
+ if (item.section === 'posts' && wentOut(deliveryOf(index, item))) {
1269
+ say.err(`The ${what} went out: deleting its record here would not take it off the network, and it is the site's history. It stays.`)
1270
+ return { exitCode: 2 }
1271
+ }
1272
+ const res = await client.writePromotionItems(site, [{ kind: 'delete', uuid: item.uuid, if_unmodified_since: item.updated_at }])
1273
+ if (!res.ok) {
1274
+ await sayRefusal(res, { site, origin: client.origin, what: 'delete it', index })
1275
+ return { exitCode: 1 }
1276
+ }
1277
+ if (json) console.log(JSON.stringify({ backend: client.origin, site, kind: kindOf(item), id: item.uuid, deleted: true }))
1278
+ else say.ok(`Deleted the ${what}.`)
1279
+ return { exitCode: 0 }
1280
+ }
1281
+
1282
+ // ── going out: send, unschedule, start, resume, pause ─────────────────────────────
1283
+
1284
+ /** A post's delivery, said: where it went out, when it will, or why it didn't. */
1285
+ function sayDelivery(index, post, delivery, id) {
1286
+ const network = index.byUuid.get(post.data?.via)?.data?.network ?? 'its network'
1287
+ if (delivery?.status === 'published') {
1288
+ say.ok(`Posted ${id} on ${network}${delivery.network_url ? `: ${delivery.network_url}` : ''}`)
1289
+ if (delivery.link) say.dim(`It links to ${delivery.link}`)
1290
+ return 0
1291
+ }
1292
+ if (delivery?.status === 'scheduled') {
1293
+ say.ok(`Scheduled ${id} on ${network} for ${post.data?.send_at ?? 'its time'}. It goes out then as it stands, under your name.`)
1294
+ return 0
1295
+ }
1296
+ if (delivery?.status === 'failed' || delivery?.status === 'refused') {
1297
+ say.err(`Not posted: ${reasonWords(delivery.reason)}${delivery.detail ? ` — ${delivery.detail}` : ''}`)
1298
+ return 1
1299
+ }
1300
+ say.warn(`The backend answered ${delivery?.status ?? 'no delivery'} for ${id}.`)
1301
+ return 0
1302
+ }
1303
+
1304
+ /**
1305
+ * `uniweb promote send <post> [--at <time> | --now]` — post it now, or at a time.
1306
+ *
1307
+ * ⭐ A POST WITH A TIME GOES OUT AT ITS TIME. Its `send_at` is the draft's own field, so `send`
1308
+ * schedules a post that holds one and posts one that holds none; `--at` sets the time first, and
1309
+ * `--now` posts it now whatever its time.
1310
+ *
1311
+ * ⭐ GIVEN ITS FILE, WHAT GOES OUT IS WHAT THE FILE SAYS. `send <file>` writes the file's draft
1312
+ * first, as `post` does: an edit not written yet is written, and a copy the app changed since is
1313
+ * refused, with nothing sent. `send <id>` sends the post as the backend holds it.
1314
+ */
1315
+ async function send(args) {
1316
+ const json = args.includes('--json')
1317
+ const arg = positionals(args)[1]
1318
+ const now = args.includes('--now')
1319
+ const atGiven = args.includes('--at')
1320
+ const time = flagValue(args, '--at')
1321
+ if (!arg) {
1322
+ say.err('Name the post: uniweb promote send <post> [--at <time> | --now]')
1323
+ return { exitCode: 2 }
1324
+ }
1325
+ if (now && atGiven) {
1326
+ say.err('`--now` and `--at` each say when — give one.')
1327
+ return { exitCode: 2 }
1328
+ }
1329
+ if (atGiven && !isTime(time)) {
1330
+ say.err('`--at` takes a time with its offset, such as 2026-11-24T09:00-05:00.')
1331
+ return { exitCode: 2 }
1332
+ }
1333
+ if (atGiven && Date.parse(time) <= Date.now()) {
1334
+ say.err(`\`--at ${time}\` has passed: give a time ahead, or send it now with --now.`)
1335
+ return { exitCode: 2 }
1336
+ }
1337
+ const file = draftFile(arg)
1338
+ const parsed = file ? parseDraft(file.text, { format: file.format, kind: 'post' }) : null
1339
+ if (parsed?.error) {
1340
+ say.err(parsed.error)
1341
+ return { exitCode: 2 }
1342
+ }
1343
+ const at = await begin(args, 'Sending a post', `send ${arg}`)
1344
+ if (!at.client) return at
1345
+ const { client, site } = at
1346
+ let index = await readIndex(client, site)
1347
+ if (!index) return { exitCode: 1 }
1348
+ // The post as the backend holds it: the one the file names (none yet for a new file), or the id's.
1349
+ let post = file ? (parsed.draft.id ? (index.byUuid.get(parsed.draft.id) ?? null) : null) : pick(index, arg, ['post'])
1350
+ if (!file && !post) return { exitCode: 2 }
1351
+ let id = post ? shortIds(index.items.map((i) => i.uuid)).get(post.uuid) : arg
1352
+ let before = post ? deliveryOf(index, post) : null
1353
+ let writes = 0
1354
+ const out = (delivery, exitCode) => {
1355
+ if (json) console.log(JSON.stringify({ backend: client.origin, site, id: post.uuid, short: id, writes, delivery }))
1356
+ return { exitCode }
1357
+ }
1358
+ if (post && wentOut(before)) {
1359
+ if (!json) say.warn(`Post ${id} went out already${before.network_url ? `: ${before.network_url}` : ''}. A new post is a new draft.`)
1360
+ return out(before, 0)
1361
+ }
1362
+
1363
+ // The time it goes out at: --at's, else the file's own send_at where it names one, else the post's.
1364
+ const held = parsed && parsed.draft.fields.send_at !== undefined ? parsed.draft.fields.send_at : (post?.data?.send_at ?? null)
1365
+ const when = now ? null : atGiven ? time : held
1366
+ if (when && !atGiven && Date.parse(when) <= Date.now()) {
1367
+ say.err(`Post ${id} holds send_at ${when}, which has passed: send it now with --now, or at another time with --at <time>.`)
1368
+ return { exitCode: 2 }
1369
+ }
1370
+ // Scheduled before this command, so a write that makes it a draft again is said if sending is refused.
1371
+ const scheduledFor = before?.status === 'scheduled' ? (post.data?.send_at ?? null) : null
1372
+
1373
+ if (file) {
1374
+ // `--at` moves the file's own send_at, so the one write carries it and the file keeps saying it.
1375
+ let text = file.text
1376
+ if (atGiven && !sameInstant(held, time)) {
1377
+ text = fileWithFields(file.text, file.format, { send_at: time })
1378
+ if (!text) {
1379
+ say.err(`Could not set the time in ${arg}: give it \`send_at: ${time}\`, then send it.`)
1380
+ return { exitCode: 2 }
1381
+ }
1382
+ }
1383
+ const draft = text === file.text ? parsed.draft : parseDraft(text, { format: file.format, kind: 'post' }).draft
1384
+ const wrote = await writeParsed({
1385
+ client,
1386
+ site,
1387
+ index,
1388
+ input: { file: file.path, shown: arg, text, dir: dirname(file.path) },
1389
+ format: file.format,
1390
+ draft,
1391
+ kind: 'post'
1392
+ })
1393
+ if (!wrote.after) return wrote
1394
+ if (wrote.fileNote && !json) say.warn(wrote.fileNote)
1395
+ writes = wrote.ops.length
1396
+ index = wrote.after
1397
+ post = index.byUuid.get(wrote.plan.uuid)
1398
+ id = shortIds(index.items.map((i) => i.uuid)).get(post.uuid)
1399
+ before = deliveryOf(index, post)
1400
+ if (writes && text === file.text && !json) say.info(`Wrote what ${arg} says to post ${id} first: it differed from the post as stored.`)
1401
+ }
1402
+
1403
+ let res
1404
+ let moved = false
1405
+ if (when) {
1406
+ if (before?.status === 'scheduled' && sameInstant(post.data?.send_at, when)) {
1407
+ if (!json) say.ok(`Post ${id} is scheduled for ${post.data.send_at} already.`)
1408
+ return out(before, 0)
1409
+ }
1410
+ if (!sameInstant(post.data?.send_at, when)) {
1411
+ // The time is the post's own field, written first. A write makes a scheduled post a draft again.
1412
+ const wrote = await client.writePromotionItems(site, [
1413
+ { kind: 'update', uuid: post.uuid, data: { ...post.data, send_at: when }, if_unmodified_since: post.updated_at }
1414
+ ])
1415
+ if (!wrote.ok) {
1416
+ await sayRefusal(wrote, { site, origin: client.origin, what: 'set its time', index })
1417
+ return { exitCode: 1 }
1418
+ }
1419
+ post.data = { ...post.data, send_at: when }
1420
+ moved = true
1421
+ writes++
1422
+ }
1423
+ res = await client.postAction(site, post.uuid, 'schedule')
1424
+ } else {
1425
+ res = await client.postAction(site, post.uuid, 'publish')
1426
+ }
1427
+ if (!res.ok) {
1428
+ await sayRefusal(res, { site, origin: client.origin, what: 'send posts', index })
1429
+ // What this command wrote stays written, so say what the post is now.
1430
+ if (scheduledFor && writes) {
1431
+ say.warn(`Post ${id} was scheduled for ${scheduledFor}, and writing to it made it a draft again${moved || (when && !sameInstant(scheduledFor, when)) ? `, its time now ${when}` : ''}: it is not scheduled now.`)
1432
+ } else if (moved) {
1433
+ say.warn(`Post ${id}'s time is ${when} now, and it is not scheduled.`)
1434
+ }
1435
+ return { exitCode: 1 }
1436
+ }
1437
+ const delivery = (await res.json().catch(() => null))?.delivery ?? null
1438
+ if (json) return out(delivery, delivery?.status === 'failed' || delivery?.status === 'refused' ? 1 : 0)
1439
+ return { exitCode: sayDelivery(index, post, delivery, id) }
1440
+ }
1441
+
1442
+ /** `uniweb promote unschedule <post>` — a scheduled post a draft again, its time kept. */
1443
+ async function unschedule(args) {
1444
+ const json = args.includes('--json')
1445
+ const arg = positionals(args)[1]
1446
+ if (!arg) {
1447
+ say.err('Name the post: uniweb promote unschedule <post>')
1448
+ return { exitCode: 2 }
1449
+ }
1450
+ const at = await begin(args, 'Unscheduling a post', `unschedule ${arg}`)
1451
+ if (!at.client) return at
1452
+ const { client, site } = at
1453
+ const index = await readIndex(client, site)
1454
+ if (!index) return { exitCode: 1 }
1455
+ const post = pick(index, arg, ['post'])
1456
+ if (!post) return { exitCode: 2 }
1457
+ const id = shortIds(index.items.map((i) => i.uuid)).get(post.uuid)
1458
+ const before = deliveryOf(index, post)
1459
+ if (before?.status !== 'scheduled') {
1460
+ if (json) console.log(JSON.stringify({ backend: client.origin, site, id: post.uuid, short: id, delivery: before }))
1461
+ else say.info(`Post ${id} is not scheduled (${before?.status ?? 'a draft'}): nothing to do.`)
1462
+ return { exitCode: 0 }
1463
+ }
1464
+ const res = await client.postAction(site, post.uuid, 'unschedule')
1465
+ if (!res.ok) {
1466
+ await sayRefusal(res, { site, origin: client.origin, what: 'unschedule posts', index })
1467
+ return { exitCode: 1 }
1468
+ }
1469
+ const delivery = (await res.json().catch(() => null))?.delivery ?? null
1470
+ if (json) console.log(JSON.stringify({ backend: client.origin, site, id: post.uuid, short: id, delivery }))
1471
+ else say.ok(`Post ${id} is a draft again, its time kept (${post.data?.send_at ?? 'none'}): uniweb promote send ${id} schedules it again.`)
1472
+ return { exitCode: 0 }
1473
+ }
1474
+
1475
+ /**
1476
+ * What starting (or resuming) a campaign in these ad accounts will spend, as far as the draft
1477
+ * says: its dates, and per account the ad groups whose ads run there, with their daily budgets
1478
+ * and the most that comes to. The currency is the account's, which the network knows.
1479
+ *
1480
+ * ⭐ A MOST IS SAID ONLY WHEN EVERY AD GROUP STATES ITS DAILY BUDGET. One without leaves what it
1481
+ * spends to the network, so the summary names it rather than add up the others as if it were the
1482
+ * whole: that total is the one number the person agrees to.
1483
+ */
1484
+ function spendSummary(index, campaign, accounts, { connections, pages }) {
1485
+ const starts = campaign.data?.starts ?? null
1486
+ const ends = campaign.data?.ends ?? null
1487
+ const days = starts && ends ? Math.round((Date.parse(ends) - Date.parse(starts)) / 86400000) + 1 : null
1488
+ return {
1489
+ name: campaign.data?.name ?? null,
1490
+ starts,
1491
+ ends,
1492
+ days: Number.isFinite(days) && days > 0 ? days : null,
1493
+ accounts: accounts.map((via) => {
1494
+ const groups = index
1495
+ .children('campaigns/ad_groups', campaign.uuid)
1496
+ .map((g) => ({ g, ads: index.children('campaigns/ad_groups/ads', g.uuid).filter((a) => a.data?.via === via) }))
1497
+ .filter((x) => x.ads.length)
1498
+ const unbudgeted = groups.filter((x) => !isAmount(x.g.data?.daily_budget)).map((x) => x.g.data?.name ?? null)
1499
+ const daily = unbudgeted.length ? null : sumAmounts(groups.map((x) => x.g.data?.daily_budget))
1500
+ const total = daily !== null && Number.isFinite(days) && days > 0 ? (Math.round(Number(daily) * 100) * days / 100).toFixed(2) : null
1501
+ return {
1502
+ via,
1503
+ account: accountName(index, via, connections),
1504
+ groups: groups.map((x) => ({ name: x.g.data?.name ?? null, daily_budget: x.g.data?.daily_budget ?? null, ads: x.ads.length })),
1505
+ daily,
1506
+ unbudgeted,
1507
+ upTo: total,
1508
+ pages: [...new Set(groups.flatMap((x) => x.ads.map((a) => pageRoute(a.data?.page, pages) ?? '(no page)')))]
1509
+ }
1510
+ })
1511
+ }
1512
+ }
1513
+
1514
+ function printSummary(summary, act) {
1515
+ const dates = summary.starts || summary.ends
1516
+ ? `${summary.starts ?? 'now'} – ${summary.ends ?? 'until paused'}${summary.days ? `, ${summary.days} day${summary.days === 1 ? '' : 's'}` : ''}`
1517
+ : 'no dates: it runs from now until paused'
1518
+ console.log(`${act === 'start' ? 'Starting' : 'Resuming'} “${summary.name ?? '?'}”, ${dates}, in the owner's ad account${summary.accounts.length === 1 ? '' : 's'}:`)
1519
+ for (const a of summary.accounts) {
1520
+ if (!a.groups.length) {
1521
+ console.log(` ${a.account}: no ad runs there yet`)
1522
+ continue
1523
+ }
1524
+ const budgets = a.groups.map((g) => (isAmount(g.daily_budget) ? money(g.daily_budget) : 'no daily budget')).join(' + ')
1525
+ console.log(` ${a.account}: ${a.groups.length} ad group${a.groups.length === 1 ? '' : 's'}, ${budgets} a day in the account's currency${a.upTo ? ` — up to ${a.upTo}` : a.unbudgeted.length || summary.ends ? '' : ', until paused'}`)
1526
+ if (a.unbudgeted.length) {
1527
+ const named = a.unbudgeted.map((n) => (n ? `“${n}”` : 'one unnamed')).join(', ')
1528
+ console.log(` ${c.yellow}No most can be said: ad group ${named} states no daily budget, so the network decides what ${a.unbudgeted.length === 1 ? 'it spends' : 'they spend'}. Give ${a.unbudgeted.length === 1 ? 'it' : 'each'} a daily_budget to bound it.${c.reset}`)
1529
+ }
1530
+ const ads = a.groups.reduce((n, g) => n + g.ads, 0)
1531
+ console.log(` ${ads} ad${ads === 1 ? '' : 's'}, linking to ${a.pages.join(', ')}`)
1532
+ }
1533
+ }
1534
+
1535
+ /** A campaign's deliveries, said: where it runs, where it waits, and why. */
1536
+ function sayDeliveries(index, deliveries, connections, act) {
1537
+ let running = 0
1538
+ for (const d of deliveries) {
1539
+ const account = accountName(index, d.via, connections)
1540
+ if (d.status === 'active') {
1541
+ running++
1542
+ say.ok(`Running in ${account}${d.review ? `, the network's review: ${reviewWords(d.review)}` : ''}${d.currency ? `, spending in ${d.currency}` : ''}`)
1543
+ } else if (d.status === 'paused') {
1544
+ say.ok(`Paused in ${account}${d.reason ? ` — ${reasonWords(d.reason)}` : ''}`)
1545
+ } else {
1546
+ say.warn(`${d.status === 'attention' ? 'Not running' : d.status} in ${account}${d.reason ? `: ${reasonWords(d.reason)}` : ''}${d.detail ? ` — ${d.detail}` : ''}`)
1547
+ }
1548
+ }
1549
+ if (act === 'start' && running) say.dim('What runs in an account is fixed there now: a change is a new ad account in its `via`, or a new campaign.')
1550
+ return deliveries.length && !running && act !== 'pause' ? 1 : 0
1551
+ }
1552
+
1553
+ /**
1554
+ * `uniweb promote start | resume <campaign> [--yes]` — spend in the owner's ad accounts.
1555
+ *
1556
+ * ⭐ IT SAYS WHAT IT WILL SPEND, THEN ASKS [Diego, 2026-11-16: "if you thing we need confirmation,
1557
+ * it can be done, with `--yes` as a way to skip it"]. At a terminal it asks; `--yes` answers, as an
1558
+ * agent passes it once its person has agreed; with neither it refuses rather than spend unseen.
1559
+ */
1560
+ async function spend(args, act) {
1561
+ const json = args.includes('--json')
1562
+ const arg = positionals(args)[1]
1563
+ if (!arg) {
1564
+ say.err(`Name the campaign: uniweb promote ${act} <campaign> [--yes]`)
1565
+ return { exitCode: 2 }
1566
+ }
1567
+ const at = await begin(args, act === 'start' ? 'Starting a campaign' : 'Resuming a campaign', `${act} ${arg}`)
1568
+ if (!at.client) return at
1569
+ const { client, site } = at
1570
+ const index = await readIndex(client, site)
1571
+ if (!index) return { exitCode: 1 }
1572
+ const campaign = pick(index, arg, ['campaign'])
1573
+ if (!campaign) return { exitCode: 2 }
1574
+ const deliveries = campaignDeliveries(index, campaign)
1575
+ const via = Array.isArray(campaign.data?.via) ? campaign.data.via : []
1576
+ const accounts =
1577
+ act === 'start'
1578
+ ? via.filter((u) => !deliveries.some((d) => d.via === u && d.external_id))
1579
+ : deliveries.filter((d) => d.external_id && d.status === 'paused').map((d) => d.via)
1580
+ const name = labelOf(index, campaign)
1581
+ if (!accounts.length) {
1582
+ const why =
1583
+ act === 'resume'
1584
+ ? `${name} is paused nowhere.`
1585
+ : via.length
1586
+ ? `${name} runs in every ad account of its \`via\` already.`
1587
+ : `${name} names no ad account yet — give it one in its \`via\`: uniweb promote campaign <file>`
1588
+ if (json) console.log(JSON.stringify({ backend: client.origin, site, id: campaign.uuid, act, accounts: [], deliveries }))
1589
+ else say.info(why)
1590
+ return { exitCode: act === 'start' && !via.length ? 2 : 0 }
1591
+ }
1592
+ const [connections, pages] = await Promise.all([listedConnections(client), readPages(client, site)])
1593
+ const summary = spendSummary(index, campaign, accounts, { connections, pages })
1594
+ if (!json) printSummary(summary, act)
1595
+ // What the campaign's pages show and what its networks will hear, before anything is spent.
1596
+ const landing = landingOf(index, campaign, pages)
1597
+ const dir = !json && landing.routes.length ? await siteFilesFor(site, client.origin) : null
1598
+ if (dir) await landingNotes(dir, landing.routes, { networks: landing.networks, goal: landing.goal })
1599
+
1600
+ if (!args.includes('--yes')) {
1601
+ if (json || isNonInteractive(args)) {
1602
+ say.err(`\`uniweb promote ${act}\` spends in the owner's ad accounts, so it asks first — pass --yes once your person has agreed to what it will spend.`)
1603
+ return { exitCode: 2 }
1604
+ }
1605
+ if (!(await confirm(`${act === 'start' ? 'Start' : 'Resume'} it?`, false))) {
1606
+ say.info(`Cancelled — nothing ${act === 'start' ? 'started' : 'resumed'}.`)
1607
+ return { exitCode: 0 }
1608
+ }
1609
+ }
1610
+ const res = await client.campaignAction(site, campaign.uuid, act)
1611
+ if (!res.ok) {
1612
+ await sayRefusal(res, { site, origin: client.origin, what: `${act} campaigns`, index })
1613
+ return { exitCode: 1 }
1614
+ }
1615
+ const answered = (await res.json().catch(() => null))?.deliveries ?? []
1616
+ if (json) {
1617
+ console.log(JSON.stringify({ backend: client.origin, site, id: campaign.uuid, act, summary, deliveries: answered }))
1618
+ return { exitCode: answered.length && !answered.some((d) => d.status === 'active') ? 1 : 0 }
1619
+ }
1620
+ return { exitCode: sayDeliveries(index, answered, connections, act) }
1621
+ }
1622
+
1623
+ /** `uniweb promote pause <campaign>` — wherever it runs. It stops the spending and asks nothing. */
1624
+ async function pause(args) {
1625
+ const json = args.includes('--json')
1626
+ const arg = positionals(args)[1]
1627
+ if (!arg) {
1628
+ say.err('Name the campaign: uniweb promote pause <campaign>')
1629
+ return { exitCode: 2 }
1630
+ }
1631
+ const at = await begin(args, 'Pausing a campaign', `pause ${arg}`)
1632
+ if (!at.client) return at
1633
+ const { client, site } = at
1634
+ const index = await readIndex(client, site)
1635
+ if (!index) return { exitCode: 1 }
1636
+ const campaign = pick(index, arg, ['campaign'])
1637
+ if (!campaign) return { exitCode: 2 }
1638
+ if (!campaignDeliveries(index, campaign).some((d) => d.external_id && d.status !== 'paused')) {
1639
+ if (json) console.log(JSON.stringify({ backend: client.origin, site, id: campaign.uuid, act: 'pause', deliveries: campaignDeliveries(index, campaign) }))
1640
+ else say.info(`${labelOf(index, campaign)} runs nowhere: nothing to pause.`)
1641
+ return { exitCode: 0 }
1642
+ }
1643
+ const res = await client.campaignAction(site, campaign.uuid, 'pause')
1644
+ if (!res.ok) {
1645
+ await sayRefusal(res, { site, origin: client.origin, what: 'pause campaigns', index })
1646
+ return { exitCode: 1 }
1647
+ }
1648
+ const answered = (await res.json().catch(() => null))?.deliveries ?? []
1649
+ if (json) {
1650
+ console.log(JSON.stringify({ backend: client.origin, site, id: campaign.uuid, act: 'pause', deliveries: answered }))
1651
+ return { exitCode: 0 }
1652
+ }
1653
+ const connections = await listedConnections(client)
1654
+ return { exitCode: sayDeliveries(index, answered, connections, 'pause') }
1655
+ }
1656
+
1657
+ // ── the command ────────────────────────────────────────────────────────────────────
1658
+
1659
+ export async function promote(args = []) {
1660
+ const badFlag = checkFlags('promote', args)
1661
+ if (badFlag) {
1662
+ say.err(badFlag.message)
1663
+ return { exitCode: 2 }
1664
+ }
1665
+ const sub = positionals(args)[0]
1666
+ try {
1667
+ if (sub === 'status') return await status(args)
1668
+ if (sub === 'check') return await check(args)
1669
+ if (sub === 'connect') return await connectNetwork(args)
1670
+ if (sub === 'post' || sub === 'campaign') return await writeDraft(args, sub)
1671
+ if (sub === 'show') return await show(args)
1672
+ if (sub === 'delete') return await deleteItem(args)
1673
+ if (sub === 'send') return await send(args)
1674
+ if (sub === 'unschedule') return await unschedule(args)
1675
+ if (sub === 'start' || sub === 'resume') return await spend(args, sub)
1676
+ if (sub === 'pause') return await pause(args)
1677
+ } catch (err) {
1678
+ say.err(err instanceof WorkspaceMismatchError ? err.message : err?.message || String(err))
1679
+ return { exitCode: 1 }
1680
+ }
1681
+ if (sub) {
1682
+ say.err(`Unknown command: uniweb promote ${sub}`)
1683
+ console.error(USAGE)
1684
+ return { exitCode: 2 }
1685
+ }
1686
+ console.log(USAGE)
1687
+ return { exitCode: 0 }
1688
+ }
1689
+
1690
+ export default promote