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.
- package/package.json +5 -5
- package/partials/agents.md +2 -1
- package/partials/guides/index.json +5 -0
- package/partials/guides/promote.md +144 -0
- package/src/backend/client.js +140 -7
- package/src/backend/promote-drafts.js +1032 -0
- package/src/backend/site-sync.js +2 -1
- package/src/commands/doctor.js +21 -5
- package/src/commands/promote.js +1690 -0
- package/src/commands/pull.js +120 -7
- package/src/commands/site.js +1 -1
- package/src/commands/status.js +169 -2
- package/src/framework-index.json +3 -3
- package/src/index.js +12 -1
- package/src/utils/flag-guard.js +6 -0
- package/src/utils/status-next.js +2 -2
|
@@ -0,0 +1,1032 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Drafts for `uniweb promote`: a post or a campaign as an agent writes it in a file, and the batch
|
|
3
|
+
* that makes the backend's copy say it.
|
|
4
|
+
*
|
|
5
|
+
* ⭐ THE BACKEND HOLDS THE ONLY COPY, AND A FILE IS ONE CLIENT'S DRAFT OF IT. A draft names what it
|
|
6
|
+
* was read at: each unit's `id` and `version`. A unit is an item with the parts of its body — a post
|
|
7
|
+
* and its parts, an ad and its parts, a campaign, an ad group — so its version covers them together.
|
|
8
|
+
* A unit changed since (in the app, or by another run) is refused, never written over: whoever wrote
|
|
9
|
+
* last reads it again (`uniweb promote show`), as the app's own editor does on a stale write.
|
|
10
|
+
*
|
|
11
|
+
* ⭐ NOTHING IS DELETED BY LEAVING IT OUT. An ad group or an ad the file doesn't hold is kept, since
|
|
12
|
+
* it may be the person's, added in the app after the agent read the campaign; `uniweb promote
|
|
13
|
+
* delete` deletes. A post's or an ad's parts are its body, read at its version, so the body the file
|
|
14
|
+
* gives is the body it gets.
|
|
15
|
+
*
|
|
16
|
+
* ⭐ THE CLI TRANSLATES ONLY WHAT THE FILES NAME DIFFERENTLY: a page by its route, an account by its
|
|
17
|
+
* network, a picture by its file. Every other field is the backend's, carried as it reads, so a field
|
|
18
|
+
* the Model adds reaches the agent with no CLI release, and an update carries back what it doesn't
|
|
19
|
+
* edit (an update replaces the item's data).
|
|
20
|
+
*
|
|
21
|
+
* Pure: the command reads, uploads and writes; this module decides.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { createHash } from 'node:crypto'
|
|
25
|
+
import yaml from 'js-yaml'
|
|
26
|
+
import {
|
|
27
|
+
buildRouteOf,
|
|
28
|
+
documentSourceLocale,
|
|
29
|
+
editYamlText,
|
|
30
|
+
pageRefIndex,
|
|
31
|
+
setYamlKeyFirst
|
|
32
|
+
} from '@uniweb/build/uwx'
|
|
33
|
+
|
|
34
|
+
/** How the build reads YAML: no implicit timestamp, so `starts: 2026-12-01` stays the text written. */
|
|
35
|
+
export const YAML_READ = Object.freeze({ schema: yaml.CORE_SCHEMA.extend({ implicit: [yaml.types.merge] }) })
|
|
36
|
+
/** How it is written: one line per value, and a string that reads as another type quoted. */
|
|
37
|
+
const YAML_WRITE = Object.freeze({ lineWidth: -1, quotingType: "'", noRefs: true })
|
|
38
|
+
|
|
39
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
40
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
41
|
+
|
|
42
|
+
// ── The promotion, indexed ─────────────────────────────────────────────────────────
|
|
43
|
+
|
|
44
|
+
/** The sections a command names an item in, and what it calls each. */
|
|
45
|
+
const KINDS = {
|
|
46
|
+
posts: 'post',
|
|
47
|
+
campaigns: 'campaign',
|
|
48
|
+
'campaigns/ad_groups': 'ad group',
|
|
49
|
+
'campaigns/ad_groups/ads': 'ad',
|
|
50
|
+
networks: 'account'
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* A promotion as the backend read it (`{ uuid, items }`), indexed: each item by uuid, and the
|
|
55
|
+
* items of a section under a parent, in the order the read gives them.
|
|
56
|
+
*
|
|
57
|
+
* @param {{ uuid?: string, items?: object[] } | null} promotion
|
|
58
|
+
*/
|
|
59
|
+
export function indexPromotion(promotion) {
|
|
60
|
+
const items = Array.isArray(promotion?.items) ? promotion.items.filter((i) => i && typeof i.uuid === 'string') : []
|
|
61
|
+
const byUuid = new Map(items.map((i) => [i.uuid, i]))
|
|
62
|
+
return {
|
|
63
|
+
uuid: promotion?.uuid ?? null,
|
|
64
|
+
items,
|
|
65
|
+
byUuid,
|
|
66
|
+
top: (section) => items.filter((i) => i.section === section),
|
|
67
|
+
children: (section, parent) => items.filter((i) => i.section === section && i.parent === parent),
|
|
68
|
+
child: (section, parent) => items.find((i) => i.section === section && i.parent === parent) ?? null
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** What a command calls an item: `post`, `campaign`, `ad group`, `ad`, `account`, or null. */
|
|
73
|
+
export function kindOf(item) {
|
|
74
|
+
return KINDS[item?.section] ?? null
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The items a unit's version covers: the item, and the parts of its body where it has them. */
|
|
78
|
+
export function unitItems(index, item) {
|
|
79
|
+
if (item?.section === 'posts') return [item, ...index.children('posts/parts', item.uuid)]
|
|
80
|
+
if (item?.section === 'campaigns/ad_groups/ads') return [item, ...index.children('campaigns/ad_groups/ads/parts', item.uuid)]
|
|
81
|
+
return item ? [item] : []
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* A unit's version: the same while none of its items is made, changed or removed. Backend's own
|
|
86
|
+
* children (a delivery) are not in it, as they never stale a draft in the app either. It leads with
|
|
87
|
+
* a letter, so YAML reads it back as the same string.
|
|
88
|
+
*/
|
|
89
|
+
export function unitVersion(items) {
|
|
90
|
+
const lines = items.filter(Boolean).map((i) => `${i.uuid}@${i.updated_at ?? ''}`).sort()
|
|
91
|
+
return `v${createHash('sha256').update(lines.join('\n')).digest('hex').slice(0, 12)}`
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function versionOf(index, item) {
|
|
95
|
+
return unitVersion(unitItems(index, item))
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Short ids, as git shortens a hash: the shortest END of each uuid, at least `min` characters,
|
|
100
|
+
* that no other uuid ends with. The end, since a uuid made by the backend leads with the time it
|
|
101
|
+
* was made, so two made in the same minute share their first characters.
|
|
102
|
+
*
|
|
103
|
+
* @param {string[]} uuids
|
|
104
|
+
* @returns {Map<string, string>}
|
|
105
|
+
*/
|
|
106
|
+
export function shortIds(uuids, min = 4) {
|
|
107
|
+
const hex = [...new Set(uuids.filter(Boolean))].map((u) => [u, String(u).replace(/-/g, '').toLowerCase()])
|
|
108
|
+
const out = new Map()
|
|
109
|
+
for (const [u, h] of hex) {
|
|
110
|
+
let n = Math.min(min, h.length)
|
|
111
|
+
while (n < h.length && hex.some(([v, g]) => v !== u && g.endsWith(h.slice(-n)))) n++
|
|
112
|
+
out.set(u, h.slice(-n))
|
|
113
|
+
}
|
|
114
|
+
return out
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Whether `ref` names `uuid`: the whole of it, or its end. */
|
|
118
|
+
export function idMatches(uuid, ref) {
|
|
119
|
+
if (typeof uuid !== 'string' || typeof ref !== 'string' || !ref) return false
|
|
120
|
+
const want = ref.replace(/-/g, '').toLowerCase()
|
|
121
|
+
return uuid.toLowerCase() === ref.toLowerCase() || (want.length >= 2 && uuid.replace(/-/g, '').toLowerCase().endsWith(want))
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The item a command names: a uuid or its end, or a campaign by its name.
|
|
126
|
+
*
|
|
127
|
+
* @returns {{ item: object } | { none: true } | { many: object[] }}
|
|
128
|
+
*/
|
|
129
|
+
export function findItem(index, ref, { kinds = ['post', 'campaign', 'ad group', 'ad'] } = {}) {
|
|
130
|
+
const pool = index.items.filter((i) => kinds.includes(kindOf(i)))
|
|
131
|
+
const exact = pool.find((i) => i.uuid.toLowerCase() === String(ref).toLowerCase())
|
|
132
|
+
if (exact) return { item: exact }
|
|
133
|
+
const byEnd = pool.filter((i) => idMatches(i.uuid, String(ref)))
|
|
134
|
+
const byName = kinds.includes('campaign')
|
|
135
|
+
? pool.filter((i) => i.section === 'campaigns' && typeof i.data?.name === 'string' && i.data.name.toLowerCase() === String(ref).toLowerCase())
|
|
136
|
+
: []
|
|
137
|
+
const found = [...new Set([...byEnd, ...byName])]
|
|
138
|
+
if (found.length === 1) return { item: found[0] }
|
|
139
|
+
return found.length ? { many: found } : { none: true }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The campaign an ad group or an ad belongs to, or the campaign itself. */
|
|
143
|
+
export function campaignOf(index, item) {
|
|
144
|
+
let at = item
|
|
145
|
+
while (at && at.section !== 'campaigns') at = index.byUuid.get(at.parent)
|
|
146
|
+
return at ?? null
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** A post's or an ad's state: its delivery's status, or `draft` while it has none. */
|
|
150
|
+
export function deliveryOf(index, item) {
|
|
151
|
+
if (item?.section === 'posts') return index.child('posts/delivery', item.uuid)?.data ?? null
|
|
152
|
+
if (item?.section === 'campaigns/ad_groups/ads') return index.child('campaigns/ad_groups/ads/delivery', item.uuid)?.data ?? null
|
|
153
|
+
return null
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** A campaign's deliveries, one per ad account it has been started in. */
|
|
157
|
+
export function campaignDeliveries(index, campaign) {
|
|
158
|
+
return index.children('campaigns/delivery', campaign.uuid).map((d) => d.data).filter(Boolean)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** A post went out, so it is not edited: published, or with a network's review. */
|
|
162
|
+
export function wentOut(delivery) {
|
|
163
|
+
return ['published', 'review', 'refused'].includes(delivery?.status)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// ── Words for the backend's codes ──────────────────────────────────────────────────
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* A reason the backend gave — a delivery's, or a refusal's — in words. One the CLI has no words
|
|
170
|
+
* for yet is shown as it is, so a reason can ship before the CLI has a sentence for it; `--json`
|
|
171
|
+
* gives the codes.
|
|
172
|
+
*/
|
|
173
|
+
export const REASONS = {
|
|
174
|
+
no_network: 'the account it goes out through is no longer chosen for the site',
|
|
175
|
+
no_connection: 'no account is connected for it',
|
|
176
|
+
site_not_published: 'the site is not published yet — publish it first',
|
|
177
|
+
no_page: 'it links to no page of the site',
|
|
178
|
+
page_gone: 'the page it links to was removed from the site',
|
|
179
|
+
page_not_published: 'the page it links to is not published in its language yet — publish the site again',
|
|
180
|
+
connection_stopped: 'its account stopped: whoever connected it left the workspace, and an admin hands it on, in the app',
|
|
181
|
+
connection_gone: 'its account was disconnected',
|
|
182
|
+
connection_needs_reconnect: 'its account needs reconnecting, by its person, in the app',
|
|
183
|
+
connection_not_permitted: 'whoever scheduled it may no longer post through its account',
|
|
184
|
+
network_not_offered: 'this backend does not offer that network',
|
|
185
|
+
network_refused: 'the network refused it',
|
|
186
|
+
promote_off: 'the site has no Promote: it comes with the site\'s Analytics, which the person turns on in the app',
|
|
187
|
+
feature_not_subscribed: 'Promote comes with the site\'s Analytics, which this site does not have yet. The person turns it on in the app'
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export function reasonWords(code) {
|
|
191
|
+
return REASONS[code] ?? code
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** A network's review of an ad, in words: `in_review` → `in review`. */
|
|
195
|
+
export const reviewWords = (code) => String(code).replace(/_/g, ' ')
|
|
196
|
+
|
|
197
|
+
/** Why a post or an ad did not go out, in words: its reason, then the network's own words; null when it gave neither. */
|
|
198
|
+
export function whyNot(delivery) {
|
|
199
|
+
const said = [delivery?.reason ? reasonWords(delivery.reason) : null, delivery?.detail || null].filter(Boolean)
|
|
200
|
+
return said.length ? said.join(' — ') : null
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* A post's states as its delivery's `status` holds them, in the order a person reads them, what
|
|
205
|
+
* needs looking at first. A post with no delivery is a draft.
|
|
206
|
+
*/
|
|
207
|
+
export const POST_STATES = ['failed', 'refused', 'draft', 'scheduled', 'review', 'published']
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Posts counted by state, every state present: the known ones in `POST_STATES`'s order, then any
|
|
211
|
+
* other as the backend gave it, so a state the CLI has no word for yet is still counted.
|
|
212
|
+
*
|
|
213
|
+
* @param {Array<string|null|undefined>} states - each post's, empty for a draft
|
|
214
|
+
* @returns {Array<[string, number]>}
|
|
215
|
+
*/
|
|
216
|
+
export function stateCounts(states) {
|
|
217
|
+
const counts = new Map()
|
|
218
|
+
for (const s of states) counts.set(s || 'draft', (counts.get(s || 'draft') ?? 0) + 1)
|
|
219
|
+
const order = [...POST_STATES.filter((s) => counts.has(s)), ...[...counts.keys()].filter((s) => !POST_STATES.includes(s))]
|
|
220
|
+
return order.map((s) => [s, counts.get(s)])
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ── The input ──────────────────────────────────────────────────────────────────────
|
|
224
|
+
|
|
225
|
+
const FRONT = /^---[ \t]*\r?\n(?:([\s\S]*?)\r?\n)?---[ \t]*(?:\r?\n|$)/
|
|
226
|
+
const PART_BREAK = /^---[ \t]*$/
|
|
227
|
+
const PICTURE_LINE = /^!\[[^\]]*\]\(\s*<?([^)\s>]+)>?(?:\s+["'][^"']*["'])?\s*\)$/
|
|
228
|
+
|
|
229
|
+
/** The keys of each unit that are its structure rather than its fields. */
|
|
230
|
+
const STRUCTURE = {
|
|
231
|
+
post: ['id', 'version', 'text', 'pictures', 'parts'],
|
|
232
|
+
campaign: ['id', 'version', 'ad_groups'],
|
|
233
|
+
'ad group': ['id', 'version', 'ads'],
|
|
234
|
+
ad: ['id', 'version', 'text', 'pictures', 'parts']
|
|
235
|
+
}
|
|
236
|
+
/** Backend's, read and never written: what `status --json` or `show --json` carry beside a draft. */
|
|
237
|
+
const BACKENDS = ['delivery', 'deliveries', 'reading', 'state', 'started', 'spend', 'uuid', 'updated_at', 'tag', 'short']
|
|
238
|
+
|
|
239
|
+
/** The format of an input: by its file's extension, else by what it holds. */
|
|
240
|
+
export function formatOf(file, text) {
|
|
241
|
+
const ext = /\.([a-z]+)$/i.exec(file || '')?.[1]?.toLowerCase()
|
|
242
|
+
if (ext === 'md' || ext === 'markdown') return 'markdown'
|
|
243
|
+
if (ext === 'yml' || ext === 'yaml') return 'yaml'
|
|
244
|
+
if (ext === 'json') return 'json'
|
|
245
|
+
const t = String(text ?? '').trimStart()
|
|
246
|
+
if (t.startsWith('{')) return 'json'
|
|
247
|
+
return FRONT.test(String(text ?? '')) ? 'markdown' : 'yaml'
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** A Markdown file's frontmatter and body. */
|
|
251
|
+
export function splitFrontmatter(text) {
|
|
252
|
+
const m = FRONT.exec(text)
|
|
253
|
+
if (!m) return { front: null, body: text }
|
|
254
|
+
return { front: m[1] ?? '', body: text.slice(m[0].length) }
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** A post's parts from a Markdown body: a `---` line between parts, a picture alone on its line. */
|
|
258
|
+
function partsFromBody(body) {
|
|
259
|
+
const parts = []
|
|
260
|
+
let lines = []
|
|
261
|
+
const flush = () => {
|
|
262
|
+
const pictures = []
|
|
263
|
+
const text = []
|
|
264
|
+
for (const line of lines) {
|
|
265
|
+
const picture = PICTURE_LINE.exec(line.trim())
|
|
266
|
+
if (picture) pictures.push(picture[1])
|
|
267
|
+
else text.push(line)
|
|
268
|
+
}
|
|
269
|
+
const words = text.join('\n').trim()
|
|
270
|
+
if (words || pictures.length) parts.push({ text: words, pictures })
|
|
271
|
+
lines = []
|
|
272
|
+
}
|
|
273
|
+
for (const line of String(body).split(/\r?\n/)) {
|
|
274
|
+
if (PART_BREAK.test(line)) flush()
|
|
275
|
+
else lines.push(line)
|
|
276
|
+
}
|
|
277
|
+
flush()
|
|
278
|
+
return parts
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function fieldsOf(obj, kind) {
|
|
282
|
+
const out = {}
|
|
283
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
284
|
+
if (!STRUCTURE[kind].includes(k) && !BACKENDS.includes(k)) out[k] = v
|
|
285
|
+
}
|
|
286
|
+
return out
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function partOf(p, where) {
|
|
290
|
+
if (typeof p === 'string') return { part: { text: p.trimEnd(), pictures: [] } }
|
|
291
|
+
if (!isPlainObject(p)) return { error: `${where}: a part is { text, pictures }` }
|
|
292
|
+
const text = p.text == null ? '' : p.text
|
|
293
|
+
if (typeof text !== 'string') return { error: `${where}: \`text\` is text` }
|
|
294
|
+
let pictures = p.pictures == null ? [] : p.pictures
|
|
295
|
+
if (typeof pictures === 'string') pictures = [pictures]
|
|
296
|
+
if (!Array.isArray(pictures) || pictures.some((x) => typeof x !== 'string' || !x)) {
|
|
297
|
+
return { error: `${where}: \`pictures\` is a list of files or addresses` }
|
|
298
|
+
}
|
|
299
|
+
return { part: { text: text.trimEnd(), pictures } }
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** A unit's parts from an object: `text` and `pictures` for one, `parts` for several, null for none given. */
|
|
303
|
+
function partsOf(obj, where) {
|
|
304
|
+
const hasParts = obj.parts !== undefined
|
|
305
|
+
const hasOne = obj.text !== undefined || obj.pictures !== undefined
|
|
306
|
+
if (hasParts && hasOne) return { error: `${where}: give its words as \`text\` and \`pictures\`, or as \`parts\`, not both` }
|
|
307
|
+
if (hasParts) {
|
|
308
|
+
if (!Array.isArray(obj.parts)) return { error: `${where}: \`parts\` is a list of { text, pictures }` }
|
|
309
|
+
const parts = []
|
|
310
|
+
for (const [i, p] of obj.parts.entries()) {
|
|
311
|
+
const one = partOf(p, `${where}, part ${i + 1}`)
|
|
312
|
+
if (one.error) return one
|
|
313
|
+
parts.push(one.part)
|
|
314
|
+
}
|
|
315
|
+
return { parts }
|
|
316
|
+
}
|
|
317
|
+
if (hasOne) {
|
|
318
|
+
const one = partOf(obj, where)
|
|
319
|
+
return one.error ? one : { parts: [one.part] }
|
|
320
|
+
}
|
|
321
|
+
return { parts: null }
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function identityOf(obj, where) {
|
|
325
|
+
const id = obj.id == null ? null : obj.id
|
|
326
|
+
const version = obj.version == null ? null : obj.version
|
|
327
|
+
if (id !== null && typeof id !== 'string') return { error: `${where}: \`id\` is the id the CLI wrote` }
|
|
328
|
+
if (version !== null && typeof version !== 'string') return { error: `${where}: \`version\` is the version the CLI wrote` }
|
|
329
|
+
if (id && !version) return { error: `${where}: it names \`id\` without the \`version\` it was read at — start from \`uniweb promote show ${id}\`` }
|
|
330
|
+
return { id, version }
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function adOf(obj, where) {
|
|
334
|
+
if (!isPlainObject(obj)) return { error: `${where}: an ad is a map of its fields` }
|
|
335
|
+
const ident = identityOf(obj, where)
|
|
336
|
+
if (ident.error) return ident
|
|
337
|
+
const parts = partsOf(obj, where)
|
|
338
|
+
if (parts.error) return parts
|
|
339
|
+
return { ad: { ...ident, fields: fieldsOf(obj, 'ad'), parts: parts.parts } }
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function adGroupOf(obj, where) {
|
|
343
|
+
if (!isPlainObject(obj)) return { error: `${where}: an ad group is a map of its fields` }
|
|
344
|
+
const ident = identityOf(obj, where)
|
|
345
|
+
if (ident.error) return ident
|
|
346
|
+
let ads = null
|
|
347
|
+
if (obj.ads !== undefined) {
|
|
348
|
+
if (!Array.isArray(obj.ads)) return { error: `${where}: \`ads\` is a list` }
|
|
349
|
+
ads = []
|
|
350
|
+
for (const [i, a] of obj.ads.entries()) {
|
|
351
|
+
const one = adOf(a, `${where}, ad ${i + 1}`)
|
|
352
|
+
if (one.error) return one
|
|
353
|
+
ads.push(one.ad)
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
return { group: { ...ident, fields: fieldsOf(obj, 'ad group'), ads } }
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* A draft from its text.
|
|
361
|
+
*
|
|
362
|
+
* A post is Markdown — its frontmatter its fields, its body its text, a `---` line between the
|
|
363
|
+
* parts of a thread, a picture alone on its line — or YAML or JSON, with `text` and `pictures`, or
|
|
364
|
+
* `parts`. A campaign is YAML or JSON, its `ad_groups` and their `ads` nested in it.
|
|
365
|
+
*
|
|
366
|
+
* @param {string} text
|
|
367
|
+
* @param {{ format: 'markdown'|'yaml'|'json', kind: 'post'|'campaign' }} opts
|
|
368
|
+
* @returns {{ draft: object } | { error: string }}
|
|
369
|
+
*/
|
|
370
|
+
export function parseDraft(text, { format, kind }) {
|
|
371
|
+
let obj
|
|
372
|
+
let body = null
|
|
373
|
+
if (format === 'markdown') {
|
|
374
|
+
if (kind !== 'post') return { error: 'A campaign is YAML or JSON, with its ad groups and their ads nested in it.' }
|
|
375
|
+
const split = splitFrontmatter(text)
|
|
376
|
+
try {
|
|
377
|
+
obj = split.front === null ? {} : (yaml.load(split.front, YAML_READ) ?? {})
|
|
378
|
+
} catch (err) {
|
|
379
|
+
return { error: `Its frontmatter is not YAML: ${err.message.split('\n')[0]}` }
|
|
380
|
+
}
|
|
381
|
+
body = split.body
|
|
382
|
+
} else {
|
|
383
|
+
try {
|
|
384
|
+
obj = format === 'json' ? JSON.parse(text) : (yaml.load(text, YAML_READ) ?? {})
|
|
385
|
+
} catch (err) {
|
|
386
|
+
return { error: `It is not ${format === 'json' ? 'JSON' : 'YAML'}: ${err.message.split('\n')[0]}` }
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
if (!isPlainObject(obj)) return { error: `A ${kind} is a map of its fields.` }
|
|
390
|
+
|
|
391
|
+
const ident = identityOf(obj, `The ${kind}`)
|
|
392
|
+
if (ident.error) return ident
|
|
393
|
+
if (kind === 'post') {
|
|
394
|
+
let parts
|
|
395
|
+
const bodyParts = body === null ? [] : partsFromBody(body)
|
|
396
|
+
if (bodyParts.length) {
|
|
397
|
+
if (obj.text !== undefined || obj.parts !== undefined || obj.pictures !== undefined) {
|
|
398
|
+
return { error: 'Its words are its body: leave `text`, `pictures` and `parts` out of the frontmatter.' }
|
|
399
|
+
}
|
|
400
|
+
parts = bodyParts
|
|
401
|
+
} else {
|
|
402
|
+
const given = partsOf(obj, 'The post')
|
|
403
|
+
if (given.error) return given
|
|
404
|
+
parts = given.parts
|
|
405
|
+
}
|
|
406
|
+
return { draft: { kind, ...ident, fields: fieldsOf(obj, 'post'), parts } }
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
let adGroups = null
|
|
410
|
+
if (obj.ad_groups !== undefined) {
|
|
411
|
+
if (!Array.isArray(obj.ad_groups)) return { error: '`ad_groups` is a list' }
|
|
412
|
+
adGroups = []
|
|
413
|
+
for (const [i, g] of obj.ad_groups.entries()) {
|
|
414
|
+
const one = adGroupOf(g, `Ad group ${i + 1}`)
|
|
415
|
+
if (one.error) return one
|
|
416
|
+
adGroups.push(one.group)
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
return { draft: { kind, ...ident, fields: fieldsOf(obj, 'campaign'), adGroups } }
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** Every picture a draft names, as written: the files among them are uploaded before it is written. */
|
|
423
|
+
export function picturesOf(draft) {
|
|
424
|
+
const out = []
|
|
425
|
+
const take = (parts) => {
|
|
426
|
+
for (const p of parts ?? []) out.push(...p.pictures)
|
|
427
|
+
}
|
|
428
|
+
take(draft.parts)
|
|
429
|
+
for (const g of draft.adGroups ?? []) for (const a of g.ads ?? []) take(a.parts)
|
|
430
|
+
return [...new Set(out)]
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** Whether a picture is an address already, kept as written, rather than a file to upload. */
|
|
434
|
+
export function isAddress(picture) {
|
|
435
|
+
return /^https?:\/\//i.test(picture)
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* The pictures the site's Promote holds, as a read gives them back, each an address on the
|
|
440
|
+
* backend's own origin: what a draft may name again as written, though it is neither a file here
|
|
441
|
+
* nor an `https:` address. Any other path is a file, and one that isn't there is refused.
|
|
442
|
+
*/
|
|
443
|
+
export function heldPictures(index) {
|
|
444
|
+
const held = new Set()
|
|
445
|
+
for (const i of index.items) {
|
|
446
|
+
if (i.section !== 'posts/parts' && i.section !== 'campaigns/ad_groups/ads/parts') continue
|
|
447
|
+
for (const p of Array.isArray(i.data?.pictures) ? i.data.pictures : []) if (typeof p === 'string') held.add(p)
|
|
448
|
+
}
|
|
449
|
+
return held
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// ── Pages, by their routes on the site as pushed ───────────────────────────────────
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* The site's pages, from its document as the backend holds it: each page's item uuid, its stable
|
|
456
|
+
* id and its route, by the build's rule (`buildRouteOf`), indexed as a `page:` link is read.
|
|
457
|
+
*
|
|
458
|
+
* @param {object} doc - the site's `@uniweb/site-content` document
|
|
459
|
+
*/
|
|
460
|
+
export function sitePages(doc) {
|
|
461
|
+
const language = documentSourceLocale(doc)
|
|
462
|
+
const list = []
|
|
463
|
+
const walk = (records, parentRoute) => {
|
|
464
|
+
for (const record of records || []) {
|
|
465
|
+
if (!isPlainObject(record)) continue
|
|
466
|
+
const route = buildRouteOf(record, parentRoute, language)
|
|
467
|
+
list.push({
|
|
468
|
+
uuid: typeof record.$uuid === 'string' ? record.$uuid : null,
|
|
469
|
+
id: typeof record.stable_id === 'string' && record.stable_id ? record.stable_id : null,
|
|
470
|
+
route,
|
|
471
|
+
dynamic: record.is_dynamic === true
|
|
472
|
+
})
|
|
473
|
+
walk(record.$children, route)
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
walk(doc?.pages, '/')
|
|
477
|
+
return { language, list, index: pageRefIndex(list), byUuid: new Map(list.filter((p) => p.uuid).map((p) => [p.uuid, p])) }
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* The page item a draft's `page` names: a route (`/holiday`), a `page:` link (`page:holiday`,
|
|
482
|
+
* `page:/holiday`), or the page's item uuid as the backend stores it.
|
|
483
|
+
*
|
|
484
|
+
* @returns {{ uuid: string|null, route?: string } | { error: string }}
|
|
485
|
+
*/
|
|
486
|
+
export function resolvePage(raw, pages, where = 'The draft') {
|
|
487
|
+
if (raw === null || raw === undefined || raw === '') return { uuid: null }
|
|
488
|
+
if (typeof raw !== 'string') return { error: `${where}: \`page\` is the page's route, such as /holiday` }
|
|
489
|
+
if (UUID.test(raw)) return { uuid: raw, route: pages?.byUuid.get(raw)?.route }
|
|
490
|
+
const target = raw.startsWith('page:') ? raw.slice('page:'.length) : raw
|
|
491
|
+
if (target.includes('#')) return { error: `${where}: a post or an ad links to a page, not to a place on it — \`page: ${raw.split('#')[0]}\`` }
|
|
492
|
+
const page = pages?.index.resolve(target)
|
|
493
|
+
if (!page?.uuid) {
|
|
494
|
+
return { error: `${where}: the site as pushed has no page ${raw}. Push it first (uniweb push), or name a page it has.` }
|
|
495
|
+
}
|
|
496
|
+
if (page.dynamic) {
|
|
497
|
+
return { error: `${where}: ${page.route} is a template for many pages, and a post or an ad links to one page.` }
|
|
498
|
+
}
|
|
499
|
+
return { uuid: page.uuid, route: page.route }
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** A page's route for a file: `/holiday`, or the uuid as stored when the site no longer has it. */
|
|
503
|
+
export function pageRoute(uuid, pages) {
|
|
504
|
+
if (!uuid) return null
|
|
505
|
+
return pages?.byUuid.get(uuid)?.route ?? uuid
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
// ── Accounts: a draft's `via` ──────────────────────────────────────────────────────
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* A `networks` item's connection, as a read gives it: an entity reference, `{ model, entity, brief }`,
|
|
512
|
+
* the connection's uuid its `entity` and its card's words in its `brief` — or the uuid alone, as a
|
|
513
|
+
* write gives it.
|
|
514
|
+
*
|
|
515
|
+
* @returns {{ uuid: string|null, name: string|null, handle: string|null, state: string|null }}
|
|
516
|
+
*/
|
|
517
|
+
export function connectionOf(value) {
|
|
518
|
+
if (typeof value === 'string') return { uuid: value, name: null, handle: null, state: null }
|
|
519
|
+
if (!isPlainObject(value)) return { uuid: null, name: null, handle: null, state: null }
|
|
520
|
+
const brief = isPlainObject(value.brief) ? value.brief : {}
|
|
521
|
+
return {
|
|
522
|
+
uuid: typeof value.entity === 'string' ? value.entity : typeof value.uuid === 'string' ? value.uuid : null,
|
|
523
|
+
name: brief.name ?? null,
|
|
524
|
+
handle: brief.handle ?? null,
|
|
525
|
+
state: brief.state ?? null
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* Resolves a draft's `via` to the site's `networks` item for that network and use — and, where the
|
|
531
|
+
* site has none, makes one in the same batch, as the app does the first time a site uses a network,
|
|
532
|
+
* through the one account of that network the caller can use.
|
|
533
|
+
*
|
|
534
|
+
* `via` is a network (`x`), `{ network, connection }` to choose among the caller's accounts there,
|
|
535
|
+
* or a `networks` item's id.
|
|
536
|
+
*
|
|
537
|
+
* @param {{ networks: object[], connections: object[]|null, mint: () => string }} ctx
|
|
538
|
+
*/
|
|
539
|
+
export function viaResolver({ networks, connections, mint }) {
|
|
540
|
+
const made = new Map()
|
|
541
|
+
const all = () => [...networks, ...[...made.values()].map((op) => ({ uuid: op.uuid, data: op.data }))]
|
|
542
|
+
const connectionIds = shortIds((connections ?? []).map((k) => k?.uuid))
|
|
543
|
+
const describe = (k) => `${connectionIds.get(k.uuid) ?? k.uuid} (“${k.card?.name || k.card?.handle || k.uuid}”${k.card?.state && k.card.state !== 'connected' ? `, ${k.card.state}` : ''})`
|
|
544
|
+
|
|
545
|
+
function make(network, connection, use, where) {
|
|
546
|
+
if (connections === null) return { error: `${where}: the site has no ${use} account on ${network} yet, and your connections could not be listed.` }
|
|
547
|
+
const reach = connections.filter((k) => k?.card?.network === network)
|
|
548
|
+
let chosen
|
|
549
|
+
if (connection) {
|
|
550
|
+
const named = reach.filter((k) => idMatches(k.uuid, connection))
|
|
551
|
+
if (named.length !== 1) {
|
|
552
|
+
return { error: `${where}: you reach no ${network} account ${connection}${reach.length ? ` — you reach ${reach.map(describe).join(', ')}` : ''}.` }
|
|
553
|
+
}
|
|
554
|
+
chosen = named[0]
|
|
555
|
+
} else {
|
|
556
|
+
const usable = reach.filter((k) => k.card?.state === 'connected')
|
|
557
|
+
if (usable.length > 1) {
|
|
558
|
+
return { error: `${where}: you reach ${usable.length} accounts on ${network} — choose one: \`via: { network: ${network}, connection: <id> }\`, from ${usable.map(describe).join(', ')}.` }
|
|
559
|
+
}
|
|
560
|
+
if (!usable.length && !reach.length) {
|
|
561
|
+
return { error: `${where}: no ${network} account is connected that you can use. The person connects one: uniweb promote connect ${network}`, connect: network }
|
|
562
|
+
}
|
|
563
|
+
chosen = usable[0] ?? reach[0]
|
|
564
|
+
}
|
|
565
|
+
if (chosen.card?.state !== 'connected') {
|
|
566
|
+
return {
|
|
567
|
+
error: chosen.card?.state === 'stopped'
|
|
568
|
+
? `${where}: the ${network} account ${describe(chosen)} stopped: its person left the workspace. An admin hands it on, in the app.`
|
|
569
|
+
: `${where}: the ${network} account ${describe(chosen)} needs reconnecting, by its person, in the app.`
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
const key = `${use}\u0000${network}\u0000${chosen.uuid}`
|
|
573
|
+
if (!made.has(key)) made.set(key, { kind: 'create', section: 'networks', uuid: mint(), data: { network, use, connection: chosen.uuid } })
|
|
574
|
+
return { uuid: made.get(key).uuid }
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
function resolve(raw, use, where) {
|
|
578
|
+
if (raw === undefined || raw === null || raw === '') return { error: `${where}: name the network it goes out on — \`via: x\`, say` }
|
|
579
|
+
const ofUse = all().filter((n) => n.data?.use === use)
|
|
580
|
+
if (typeof raw === 'string') {
|
|
581
|
+
const byId = ofUse.filter((n) => idMatches(n.uuid, raw))
|
|
582
|
+
if (byId.length === 1) return { uuid: byId[0].uuid }
|
|
583
|
+
const same = ofUse.filter((n) => n.data?.network === raw)
|
|
584
|
+
if (same.length === 1) return { uuid: same[0].uuid }
|
|
585
|
+
if (same.length > 1) {
|
|
586
|
+
const ids = shortIds(networks.map((n) => n.uuid))
|
|
587
|
+
const named = (n) => n.data?.target?.name ?? connectionOf(n.data?.connection).name ?? '?'
|
|
588
|
+
return { error: `${where}: the site goes out on ${raw} through ${same.length} accounts — name one by its id: ${same.map((n) => `${ids.get(n.uuid) ?? n.uuid} (“${named(n)}”)`).join(', ')}.` }
|
|
589
|
+
}
|
|
590
|
+
return make(raw, null, use, where)
|
|
591
|
+
}
|
|
592
|
+
if (isPlainObject(raw) && typeof raw.network === 'string' && raw.network) {
|
|
593
|
+
const connection = raw.connection == null ? null : String(raw.connection)
|
|
594
|
+
if (!connection) return resolve(raw.network, use, where)
|
|
595
|
+
const same = ofUse.filter((n) => n.data?.network === raw.network && idMatches(connectionOf(n.data?.connection).uuid, connection))
|
|
596
|
+
if (same.length === 1) return { uuid: same[0].uuid }
|
|
597
|
+
return make(raw.network, connection, use, where)
|
|
598
|
+
}
|
|
599
|
+
return { error: `${where}: \`via\` is a network, such as x, or { network, connection }` }
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
return { resolve, creates: () => [...made.values()] }
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* A `networks` item's name in a file: its network, where the site has one item of that use there,
|
|
607
|
+
* else its uuid.
|
|
608
|
+
*/
|
|
609
|
+
export function viaName(index, uuid) {
|
|
610
|
+
const item = index.byUuid.get(uuid)
|
|
611
|
+
if (!item || item.section !== 'networks') return uuid
|
|
612
|
+
const same = index.top('networks').filter((n) => n.data?.use === item.data?.use && n.data?.network === item.data?.network)
|
|
613
|
+
return same.length === 1 && item.data?.network ? item.data.network : uuid
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// ── The write ──────────────────────────────────────────────────────────────────────
|
|
617
|
+
|
|
618
|
+
/** Two data values the same, whatever their key order. */
|
|
619
|
+
export function sameData(a, b) {
|
|
620
|
+
const norm = (v) =>
|
|
621
|
+
Array.isArray(v)
|
|
622
|
+
? v.map(norm)
|
|
623
|
+
: isPlainObject(v)
|
|
624
|
+
? Object.fromEntries(Object.keys(v).sort().map((k) => [k, norm(v[k])]))
|
|
625
|
+
: v
|
|
626
|
+
return JSON.stringify(norm(a ?? {})) === JSON.stringify(norm(b ?? {}))
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** An item's data: what it holds, with the fields the draft gives over it, and a `null` removing one. */
|
|
630
|
+
function merged(stored, fields) {
|
|
631
|
+
const out = { ...(stored ?? {}) }
|
|
632
|
+
for (const [k, v] of Object.entries(fields)) {
|
|
633
|
+
if (v === undefined) continue
|
|
634
|
+
if (v === null) delete out[k]
|
|
635
|
+
else out[k] = v
|
|
636
|
+
}
|
|
637
|
+
return out
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
function partData(stored, part) {
|
|
641
|
+
const out = { ...(stored ?? {}) }
|
|
642
|
+
if (part.text) out.text = part.text
|
|
643
|
+
else delete out.text
|
|
644
|
+
if (part.pictures.length) out.pictures = part.pictures
|
|
645
|
+
else delete out.pictures
|
|
646
|
+
return out
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/** A body's parts, by position: each changed one updated, a new one added last, one past the end removed. */
|
|
650
|
+
function partOps(section, stored, parent, parts, mint) {
|
|
651
|
+
if (parts === null) return []
|
|
652
|
+
const ops = []
|
|
653
|
+
for (let i = 0; i < Math.max(stored.length, parts.length); i++) {
|
|
654
|
+
const s = stored[i]
|
|
655
|
+
const p = parts[i]
|
|
656
|
+
if (s && p) {
|
|
657
|
+
const data = partData(s.data, p)
|
|
658
|
+
if (!sameData(s.data, data)) ops.push({ kind: 'update', uuid: s.uuid, data, if_unmodified_since: s.updated_at })
|
|
659
|
+
} else if (p) {
|
|
660
|
+
ops.push({ kind: 'create', section, parent, uuid: mint(), data: partData(null, p), position: 'last' })
|
|
661
|
+
} else {
|
|
662
|
+
ops.push({ kind: 'delete', uuid: s.uuid, if_unmodified_since: s.updated_at })
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
return ops
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/**
|
|
669
|
+
* Whether the units a draft names are still as it read them, and are its to write: each `id` an
|
|
670
|
+
* item of the right kind, where the draft holds it, at its `version`; and a post not gone out.
|
|
671
|
+
*
|
|
672
|
+
* @returns {string[]} what refuses it, in words; empty when it may be written
|
|
673
|
+
*/
|
|
674
|
+
export function checkDraft(index, draft) {
|
|
675
|
+
const problems = []
|
|
676
|
+
const stale = (what, item) =>
|
|
677
|
+
`${what} changed since your copy — in the app, or by another run. \`uniweb promote show ${shortIds(index.items.map((i) => i.uuid)).get(item.uuid) ?? item.uuid}\` prints it as it stands now; take your changes into that.`
|
|
678
|
+
const unit = (want, d, what, parent) => {
|
|
679
|
+
if (!d.id) return null
|
|
680
|
+
const item = index.byUuid.get(d.id)
|
|
681
|
+
if (!item || item.section !== want || (parent !== undefined && item.parent !== parent)) {
|
|
682
|
+
problems.push(
|
|
683
|
+
item && item.section === want
|
|
684
|
+
? `${what} ${d.id} is not in the ${want === 'campaigns/ad_groups' ? 'campaign' : 'ad group'} it is under in your file — it moves in the app.`
|
|
685
|
+
: `${what} ${d.id} is not on this site — removed in the app? Drop its \`id\` and \`version\` to make it again.`
|
|
686
|
+
)
|
|
687
|
+
return null
|
|
688
|
+
}
|
|
689
|
+
if (versionOf(index, item) !== d.version) problems.push(stale(what, item))
|
|
690
|
+
return item
|
|
691
|
+
}
|
|
692
|
+
if (draft.kind === 'post') {
|
|
693
|
+
const post = unit('posts', draft, 'The post')
|
|
694
|
+
if (post && wentOut(deliveryOf(index, post))) {
|
|
695
|
+
problems.push('The post went out, so it isn\'t edited. Draft a new one: drop `id` and `version` from the file.')
|
|
696
|
+
}
|
|
697
|
+
return problems
|
|
698
|
+
}
|
|
699
|
+
const campaign = unit('campaigns', draft, 'The campaign')
|
|
700
|
+
for (const [i, g] of (draft.adGroups ?? []).entries()) {
|
|
701
|
+
const what = `Ad group ${i + 1}`
|
|
702
|
+
let group = null
|
|
703
|
+
if (g.id) {
|
|
704
|
+
if (!draft.id) {
|
|
705
|
+
problems.push(`${what} names an id, and the campaign none: a new campaign's ad groups are new too.`)
|
|
706
|
+
continue
|
|
707
|
+
}
|
|
708
|
+
if (!campaign) continue
|
|
709
|
+
group = unit('campaigns/ad_groups', g, what, campaign.uuid)
|
|
710
|
+
if (!group) continue
|
|
711
|
+
}
|
|
712
|
+
for (const [j, a] of (g.ads ?? []).entries()) {
|
|
713
|
+
if (!a.id) continue
|
|
714
|
+
const adWhat = `Ad ${j + 1} of ad group ${i + 1}`
|
|
715
|
+
if (!group) problems.push(`${adWhat} names an id, and its ad group none: a new ad group's ads are new too.`)
|
|
716
|
+
else unit('campaigns/ad_groups/ads', a, adWhat, group.uuid)
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
return problems
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* The batch that makes the backend's post say what the draft says, its fields already in the
|
|
724
|
+
* backend's terms (`via` and `page` as item uuids, pictures as addresses).
|
|
725
|
+
*
|
|
726
|
+
* @returns {{ ops: object[], uuid: string }}
|
|
727
|
+
*/
|
|
728
|
+
export function planPost(index, draft, { mint, language }) {
|
|
729
|
+
const stored = draft.id ? index.byUuid.get(draft.id) : null
|
|
730
|
+
const uuid = stored?.uuid ?? mint()
|
|
731
|
+
const data = merged(stored?.data, draft.fields)
|
|
732
|
+
if (!stored && data.language == null && language) data.language = language
|
|
733
|
+
const ops = []
|
|
734
|
+
if (!stored) ops.push({ kind: 'create', section: 'posts', uuid, data })
|
|
735
|
+
else if (!sameData(stored.data, data)) ops.push({ kind: 'update', uuid, data, if_unmodified_since: stored.updated_at })
|
|
736
|
+
ops.push(...partOps('posts/parts', stored ? index.children('posts/parts', uuid) : [], uuid, draft.parts, mint))
|
|
737
|
+
return { ops, uuid }
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/**
|
|
741
|
+
* The batch for a campaign, with its ad groups and ads: each named one updated where it changed,
|
|
742
|
+
* each new one made, and each the file leaves out kept and reported (`kept`).
|
|
743
|
+
*
|
|
744
|
+
* @returns {{ ops: object[], uuid: string, groups: Array<{ uuid: string, ads: string[] }>, kept: object[] }}
|
|
745
|
+
*/
|
|
746
|
+
export function planCampaign(index, draft, { mint, language }) {
|
|
747
|
+
const stored = draft.id ? index.byUuid.get(draft.id) : null
|
|
748
|
+
const uuid = stored?.uuid ?? mint()
|
|
749
|
+
const ops = []
|
|
750
|
+
const data = merged(stored?.data, draft.fields)
|
|
751
|
+
if (!stored) ops.push({ kind: 'create', section: 'campaigns', uuid, data })
|
|
752
|
+
else if (!sameData(stored.data, data)) ops.push({ kind: 'update', uuid, data, if_unmodified_since: stored.updated_at })
|
|
753
|
+
|
|
754
|
+
const groups = []
|
|
755
|
+
const kept = []
|
|
756
|
+
if (draft.adGroups !== null) {
|
|
757
|
+
const storedGroups = stored ? index.children('campaigns/ad_groups', uuid) : []
|
|
758
|
+
const named = new Set()
|
|
759
|
+
for (const g of draft.adGroups) {
|
|
760
|
+
const sg = g.id ? storedGroups.find((x) => x.uuid === g.id) : null
|
|
761
|
+
const gUuid = sg?.uuid ?? mint()
|
|
762
|
+
named.add(gUuid)
|
|
763
|
+
const gData = merged(sg?.data, g.fields)
|
|
764
|
+
if (!sg) ops.push({ kind: 'create', section: 'campaigns/ad_groups', parent: uuid, uuid: gUuid, data: gData, position: 'last' })
|
|
765
|
+
else if (!sameData(sg.data, gData)) ops.push({ kind: 'update', uuid: gUuid, data: gData, if_unmodified_since: sg.updated_at })
|
|
766
|
+
const ads = []
|
|
767
|
+
if (g.ads !== null) {
|
|
768
|
+
const storedAds = sg ? index.children('campaigns/ad_groups/ads', gUuid) : []
|
|
769
|
+
const namedAds = new Set()
|
|
770
|
+
for (const a of g.ads) {
|
|
771
|
+
const sa = a.id ? storedAds.find((x) => x.uuid === a.id) : null
|
|
772
|
+
const aUuid = sa?.uuid ?? mint()
|
|
773
|
+
namedAds.add(aUuid)
|
|
774
|
+
ads.push(aUuid)
|
|
775
|
+
const aData = merged(sa?.data, a.fields)
|
|
776
|
+
if (!sa && aData.language == null && language) aData.language = language
|
|
777
|
+
if (!sa) ops.push({ kind: 'create', section: 'campaigns/ad_groups/ads', parent: gUuid, uuid: aUuid, data: aData, position: 'last' })
|
|
778
|
+
else if (!sameData(sa.data, aData)) ops.push({ kind: 'update', uuid: aUuid, data: aData, if_unmodified_since: sa.updated_at })
|
|
779
|
+
ops.push(...partOps('campaigns/ad_groups/ads/parts', sa ? index.children('campaigns/ad_groups/ads/parts', aUuid) : [], aUuid, a.parts, mint))
|
|
780
|
+
}
|
|
781
|
+
for (const sa of storedAds) if (!namedAds.has(sa.uuid)) kept.push({ kind: 'ad', uuid: sa.uuid, name: sa.data?.headlines?.[0] ?? null, group: sg?.data?.name ?? null })
|
|
782
|
+
}
|
|
783
|
+
groups.push({ uuid: gUuid, ads })
|
|
784
|
+
}
|
|
785
|
+
for (const sg of storedGroups) if (!named.has(sg.uuid)) kept.push({ kind: 'ad group', uuid: sg.uuid, name: sg.data?.name ?? null })
|
|
786
|
+
}
|
|
787
|
+
return { ops, uuid, groups, kept }
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
// ── What `show` prints, and the ids a write leaves in the file ────────────────────
|
|
791
|
+
|
|
792
|
+
const POST_ORDER = ['via', 'language', 'page', 'send_at']
|
|
793
|
+
const CAMPAIGN_ORDER = ['name', 'goal', 'devices', 'starts', 'ends', 'via']
|
|
794
|
+
const GROUP_ORDER = ['name', 'daily_budget']
|
|
795
|
+
const AD_ORDER = ['via', 'language', 'page', 'headlines', 'descriptions']
|
|
796
|
+
const NOT_SHOWN = ['tag']
|
|
797
|
+
|
|
798
|
+
function ordered(data, order, translate) {
|
|
799
|
+
const out = {}
|
|
800
|
+
for (const k of order) if (data?.[k] !== undefined) out[k] = translate(k, data[k])
|
|
801
|
+
for (const k of Object.keys(data ?? {}).sort()) {
|
|
802
|
+
if (!order.includes(k) && !NOT_SHOWN.includes(k)) out[k] = data[k]
|
|
803
|
+
}
|
|
804
|
+
return out
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
function bodyOf(parts) {
|
|
808
|
+
const list = parts.map((p) => ({ text: p.data?.text ?? '', pictures: Array.isArray(p.data?.pictures) ? p.data.pictures : [] }))
|
|
809
|
+
return list
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
function withBody(shape, parts) {
|
|
813
|
+
if (parts.length === 1) {
|
|
814
|
+
if (parts[0].text) shape.text = parts[0].text
|
|
815
|
+
if (parts[0].pictures.length) shape.pictures = parts[0].pictures
|
|
816
|
+
} else if (parts.length > 1) {
|
|
817
|
+
shape.parts = parts.map((p) => ({ ...(p.text ? { text: p.text } : {}), ...(p.pictures.length ? { pictures: p.pictures } : {}) }))
|
|
818
|
+
}
|
|
819
|
+
return shape
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
/**
|
|
823
|
+
* A post as a draft holds it — `id`, `version`, its fields with `via` and `page` named as files
|
|
824
|
+
* name them, and its parts — so `show` and `post` round-trip.
|
|
825
|
+
*/
|
|
826
|
+
export function postShape(index, post, pages) {
|
|
827
|
+
const translate = (k, v) => (k === 'via' ? viaName(index, v) : k === 'page' ? pageRoute(v, pages) : v)
|
|
828
|
+
return {
|
|
829
|
+
id: post.uuid,
|
|
830
|
+
version: versionOf(index, post),
|
|
831
|
+
...ordered(post.data, POST_ORDER, translate),
|
|
832
|
+
parts: bodyOf(index.children('posts/parts', post.uuid))
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/** A campaign as a draft holds it, its ad groups and their ads nested in it. */
|
|
837
|
+
export function campaignShape(index, campaign, pages) {
|
|
838
|
+
const translate = (k, v) =>
|
|
839
|
+
k === 'via' ? (Array.isArray(v) ? v.map((u) => viaName(index, u)) : viaName(index, v)) : k === 'page' ? pageRoute(v, pages) : v
|
|
840
|
+
const groups = index.children('campaigns/ad_groups', campaign.uuid).map((g) => ({
|
|
841
|
+
id: g.uuid,
|
|
842
|
+
version: versionOf(index, g),
|
|
843
|
+
...ordered(g.data, GROUP_ORDER, translate),
|
|
844
|
+
ads: index.children('campaigns/ad_groups/ads', g.uuid).map((a) =>
|
|
845
|
+
withBody(
|
|
846
|
+
{ id: a.uuid, version: versionOf(index, a), ...ordered(a.data, AD_ORDER, translate) },
|
|
847
|
+
bodyOf(index.children('campaigns/ad_groups/ads/parts', a.uuid))
|
|
848
|
+
)
|
|
849
|
+
)
|
|
850
|
+
}))
|
|
851
|
+
return { id: campaign.uuid, version: versionOf(index, campaign), ...ordered(campaign.data, CAMPAIGN_ORDER, translate), ad_groups: groups }
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/** Whether a post's parts can be written as a Markdown body, and read back the same. */
|
|
855
|
+
function markdownHolds(parts) {
|
|
856
|
+
return parts.every(
|
|
857
|
+
(p) => !p.text.split('\n').some((line) => PART_BREAK.test(line) || PICTURE_LINE.test(line.trim())) && p.pictures.every((a) => !/[\s)]/.test(a))
|
|
858
|
+
)
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
/**
|
|
862
|
+
* A post's shape as a Markdown file: its fields as frontmatter, its parts as the body. Null when
|
|
863
|
+
* its words would not read back the same (a line of `---` in them, say); YAML holds it then.
|
|
864
|
+
*/
|
|
865
|
+
export function postMarkdown(shape) {
|
|
866
|
+
const { parts, ...front } = shape
|
|
867
|
+
if (!markdownHolds(parts)) return null
|
|
868
|
+
const body = parts
|
|
869
|
+
.map((p) => [p.text, ...p.pictures.map((a) => ``)].filter(Boolean).join('\n\n'))
|
|
870
|
+
.join('\n\n---\n\n')
|
|
871
|
+
return `---\n${yaml.dump(front, YAML_WRITE)}---\n${body ? `\n${body}\n` : ''}`
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
/** A shape as YAML, for a campaign, or a post Markdown cannot hold. */
|
|
875
|
+
export function shapeYaml(shape) {
|
|
876
|
+
if (Array.isArray(shape.parts)) return yaml.dump(withBody(Object.fromEntries(Object.entries(shape).filter(([k]) => k !== 'parts')), shape.parts), YAML_WRITE)
|
|
877
|
+
return yaml.dump(shape, YAML_WRITE)
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/** `{ id, version, ...rest }` — the identity a sync writes leads its map. */
|
|
881
|
+
function leading(obj, id, version) {
|
|
882
|
+
const { id: _id, version: _version, ...rest } = obj
|
|
883
|
+
return { id, version, ...rest }
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/**
|
|
887
|
+
* The draft's file once a write has landed: each unit it holds names its `id` and `version`, so the
|
|
888
|
+
* next run updates the same draft, and a teammate with the file updates it too. Everything else in
|
|
889
|
+
* the file is left as its author wrote it where the format allows (YAML's comments, a Markdown body).
|
|
890
|
+
*
|
|
891
|
+
* @param {string} text - the file as it was read
|
|
892
|
+
* @param {{ format: string, kind: string }} input
|
|
893
|
+
* @param {{ uuid: string, groups?: Array<{ uuid: string, ads: string[] }> }} map - the units the write
|
|
894
|
+
* made or named, in the file's order
|
|
895
|
+
* @param {(uuid: string) => string} version - each unit's version after the write
|
|
896
|
+
* @returns {{ text: string, whole?: boolean } | null} null when the file could not be read again
|
|
897
|
+
*/
|
|
898
|
+
export function fileWithIdentity(text, { format, kind }, map, version) {
|
|
899
|
+
const nested = (obj) => {
|
|
900
|
+
if (kind !== 'campaign' || !Array.isArray(obj.ad_groups) || !map.groups) return obj
|
|
901
|
+
return {
|
|
902
|
+
...obj,
|
|
903
|
+
ad_groups: obj.ad_groups.map((g, i) => {
|
|
904
|
+
const gm = map.groups[i]
|
|
905
|
+
if (!gm || !isPlainObject(g)) return g
|
|
906
|
+
const ads = Array.isArray(g.ads) ? g.ads.map((a, j) => (gm.ads[j] && isPlainObject(a) ? leading(a, gm.ads[j], version(gm.ads[j])) : a)) : g.ads
|
|
907
|
+
return leading(ads === undefined ? g : { ...g, ads }, gm.uuid, version(gm.uuid))
|
|
908
|
+
})
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
if (format === 'json') {
|
|
912
|
+
let obj
|
|
913
|
+
try {
|
|
914
|
+
obj = JSON.parse(text)
|
|
915
|
+
} catch {
|
|
916
|
+
return null
|
|
917
|
+
}
|
|
918
|
+
return { text: `${JSON.stringify(leading(nested(obj), map.uuid, version(map.uuid)), null, 2)}\n` }
|
|
919
|
+
}
|
|
920
|
+
const lead = (yamlText) => {
|
|
921
|
+
const withVersion = setYamlKeyFirst(yamlText, 'version', version(map.uuid))
|
|
922
|
+
return withVersion === null ? null : setYamlKeyFirst(withVersion, 'id', map.uuid)
|
|
923
|
+
}
|
|
924
|
+
if (format === 'markdown') {
|
|
925
|
+
const split = splitFrontmatter(text)
|
|
926
|
+
if (split.front === null) {
|
|
927
|
+
return { text: `---\n${yaml.dump({ id: map.uuid, version: version(map.uuid) }, YAML_WRITE)}---\n${text}` }
|
|
928
|
+
}
|
|
929
|
+
const front = lead(split.front === '' ? '' : `${split.front}\n`)
|
|
930
|
+
if (front === null) return null
|
|
931
|
+
return { text: `---\n${front.endsWith('\n') ? front : `${front}\n`}---\n${split.body}` }
|
|
932
|
+
}
|
|
933
|
+
let before
|
|
934
|
+
try {
|
|
935
|
+
before = yaml.load(text, YAML_READ) ?? {}
|
|
936
|
+
} catch {
|
|
937
|
+
return null
|
|
938
|
+
}
|
|
939
|
+
if (!isPlainObject(before)) return null
|
|
940
|
+
const after = nested(before)
|
|
941
|
+
const edited = after === before ? text : editYamlText(text, before, after)
|
|
942
|
+
const done = edited === null ? null : lead(edited)
|
|
943
|
+
if (done !== null) return { text: done }
|
|
944
|
+
return { text: yaml.dump(leading(after, map.uuid, version(map.uuid)), YAML_WRITE), whole: true }
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
// ── What a network will hear ───────────────────────────────────────────────────────
|
|
948
|
+
|
|
949
|
+
/**
|
|
950
|
+
* The site's services row a network's conversions go out through: the host sends X and Meta the
|
|
951
|
+
* site's conversions from its servers, each name mapped to the network's event.
|
|
952
|
+
*/
|
|
953
|
+
const CONVERSION_ROWS = { x: 'x', facebook: 'meta' }
|
|
954
|
+
|
|
955
|
+
/**
|
|
956
|
+
* What a network will hear of the site's conversions, from its `site.yml`: whether the site asks
|
|
957
|
+
* for tracking, the conversions it lists, and — for a campaign that optimizes for conversions —
|
|
958
|
+
* whether each network it runs on has them mapped to its events. Notes, never a gate: whoever sends
|
|
959
|
+
* or starts decides, with them in front of them.
|
|
960
|
+
*
|
|
961
|
+
* @param {object|null} siteYml
|
|
962
|
+
* @param {{ networks?: string[], goal?: string|null }} [opts] - the networks a draft goes out on;
|
|
963
|
+
* with no networks, each the site maps (`services.x`, `services.meta`)
|
|
964
|
+
* @returns {Array<{ ok: boolean, id: string, text: string }>}
|
|
965
|
+
*/
|
|
966
|
+
export function conversionNotes(siteYml, { networks = null, goal = null } = {}) {
|
|
967
|
+
const services = isPlainObject(siteYml?.services) ? siteYml.services : {}
|
|
968
|
+
const tracking = services.tracking
|
|
969
|
+
const on = tracking === true || (typeof tracking === 'string' && tracking !== '') || (isPlainObject(tracking) && tracking.enabled !== false)
|
|
970
|
+
if (!on) {
|
|
971
|
+
return [{ ok: false, id: 'tracking-off', text: 'site.yml does not ask for `services.tracking`, so the site reports no visit or conversion for a network to hear (`uniweb guide services`)' }]
|
|
972
|
+
}
|
|
973
|
+
const notes = []
|
|
974
|
+
const listed = isPlainObject(tracking) && Array.isArray(tracking.conversions)
|
|
975
|
+
? tracking.conversions.map((c) => c?.name).filter((n) => typeof n === 'string' && n)
|
|
976
|
+
: []
|
|
977
|
+
notes.push(
|
|
978
|
+
listed.length
|
|
979
|
+
? { ok: true, id: 'conversions-listed', text: `the site counts the conversion${listed.length === 1 ? '' : 's'} it lists: ${listed.join(', ')}` }
|
|
980
|
+
: { ok: false, id: 'conversions-none', text: 'the site lists no conversion of its own in `services.tracking.conversions`: it counts phone and email taps, and what its foundation reports' }
|
|
981
|
+
)
|
|
982
|
+
if (goal !== 'conversions') return notes
|
|
983
|
+
const asked = networks ?? Object.keys(CONVERSION_ROWS).filter((n) => services[CONVERSION_ROWS[n]])
|
|
984
|
+
for (const network of [...new Set(asked)]) {
|
|
985
|
+
const row = CONVERSION_ROWS[network]
|
|
986
|
+
if (!row) continue
|
|
987
|
+
const events = isPlainObject(services[row]?.events) ? Object.keys(services[row].events) : []
|
|
988
|
+
if (!events.length) {
|
|
989
|
+
notes.push({ ok: false, id: 'network-hears-none', text: `${network} hears none of the site's conversions: \`services.${row}\` maps none to its events, so a campaign there optimizes for clicks (\`uniweb guide services\`, X and Meta)` })
|
|
990
|
+
} else {
|
|
991
|
+
const unheard = listed.filter((n) => !events.includes(n))
|
|
992
|
+
notes.push({ ok: true, id: 'network-hears', text: `${network} hears ${events.join(', ')}${unheard.length ? ` — not ${unheard.join(', ')}` : ''}` })
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
return notes
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
/**
|
|
999
|
+
* A draft's file with top-level fields set where they stand, editing nothing else: a post's new
|
|
1000
|
+
* `send_at` and `version` once `send --at` has moved its time, so the file still says what the
|
|
1001
|
+
* backend holds. Null when the file cannot be read again.
|
|
1002
|
+
*
|
|
1003
|
+
* @param {string} text
|
|
1004
|
+
* @param {'markdown'|'yaml'|'json'} format
|
|
1005
|
+
* @param {object} fields
|
|
1006
|
+
* @returns {string|null}
|
|
1007
|
+
*/
|
|
1008
|
+
export function fileWithFields(text, format, fields) {
|
|
1009
|
+
if (format === 'json') {
|
|
1010
|
+
try {
|
|
1011
|
+
return `${JSON.stringify({ ...JSON.parse(text), ...fields }, null, 2)}\n`
|
|
1012
|
+
} catch {
|
|
1013
|
+
return null
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
const edit = (yamlText) => {
|
|
1017
|
+
let before
|
|
1018
|
+
try {
|
|
1019
|
+
before = yaml.load(yamlText, YAML_READ) ?? {}
|
|
1020
|
+
} catch {
|
|
1021
|
+
return null
|
|
1022
|
+
}
|
|
1023
|
+
return isPlainObject(before) ? editYamlText(yamlText, before, { ...before, ...fields }) : null
|
|
1024
|
+
}
|
|
1025
|
+
if (format === 'markdown') {
|
|
1026
|
+
const split = splitFrontmatter(text)
|
|
1027
|
+
if (split.front === null) return null
|
|
1028
|
+
const front = edit(split.front === '' ? '' : `${split.front}\n`)
|
|
1029
|
+
return front === null ? null : `---\n${front.endsWith('\n') ? front : `${front}\n`}---\n${split.body}`
|
|
1030
|
+
}
|
|
1031
|
+
return edit(text)
|
|
1032
|
+
}
|