uniweb 1.35.2 → 1.35.4

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "uniweb",
3
- "version": "1.35.2",
3
+ "version": "1.35.4",
4
4
  "description": "Create structured Vite + React sites with content/code separation",
5
5
  "type": "module",
6
6
  "bin": {
@@ -41,15 +41,15 @@
41
41
  "js-yaml": "^4.3.2",
42
42
  "prompts": "^2.4.2",
43
43
  "tar": "^7.5.21",
44
+ "@uniweb/content-writer": "~1.3.2",
44
45
  "@uniweb/core": "~1.6.13",
45
46
  "@uniweb/semantic-parser": "~1.13.5",
46
- "@uniweb/content-writer": "~1.3.2",
47
47
  "@uniweb/schemas": "~1.7.4"
48
48
  },
49
49
  "peerDependencies": {
50
- "@uniweb/build": "~1.24.1",
50
+ "@uniweb/content-reader": "~1.5.11",
51
51
  "@uniweb/semantic-parser": "~1.13.5",
52
- "@uniweb/content-reader": "~1.5.11"
52
+ "@uniweb/build": "~1.24.3"
53
53
  },
54
54
  "peerDependenciesMeta": {
55
55
  "@uniweb/build": {
@@ -136,6 +136,27 @@ await checkout(offering) // sends the buyer to pay; a free one-off is he
136
136
  - `useEntitlements()` — what the viewer holds, for "My courses". `useHolders({ schema, uuid })` — who holds a record, for a roster: its owner's or an `admin`'s to read, `forbidden` for anyone else, so draw nothing.
137
137
  - Why a checkout was refused: `error.extensions.reason` — `payments_not_ready`, `coupon_not_applicable` (with `cause`), `not_for_sale`.
138
138
 
139
+ **Prices for visitors who aren't signed in** come as records, so the first page a visit lands on already shows them, to people and to search engines. A section declares the store's catalog, a site query reads it, and the site's `blueprint.yml` opens it to visitors:
140
+
141
+ ```yaml
142
+ # queries.yml
143
+ store: { schema: '@uniweb/catalog' }
144
+ # blueprint.yml
145
+ publicQueries:
146
+ '@uniweb/catalog': { whole: true }
147
+ ```
148
+
149
+ ```jsx
150
+ // meta.js: data: { store: { schema: '@uniweb/catalog', whole: true } }
151
+ const catalogs = content.data.store // [{ info: { name, currency }, offering: [{ entry: { schema, entity, brief }, price, currency?, charge_kind }] }]
152
+ ```
153
+
154
+ - Join each record to the offering whose `entry.entity` is its uuid. `price` is in the currency's smallest unit, and `currency` is the offering's own or else `info.currency`.
155
+ - More than one catalog means none is the store, and a buyer can't pay: show no price.
156
+ - It needs the site's backend and Live Records (`records: true`). Buying, and anything that is one member's own, is `useStore()` after sign-in.
157
+ - A price the owner changes reaches visitors within about five minutes: the host keeps each answer that long, by design.
158
+ - The catalog is the backend's, written by the owner in the app, so a build and a push refuse `records/uniweb/catalog/` files.
159
+
139
160
  ## The inbox
140
161
 
141
162
  ```jsx
@@ -220,6 +241,10 @@ Nested items in one create: give an item `uuid: uuidv7()` and a later item names
220
241
 
221
242
  **Sent twice, made once:** give a create the new entry's own `uuid`, made once when the person starts adding it (`const [uuid] = useState(uuidv7)`), and a second click or a retry answers with the entry the first one made. Without it, each call makes an entry.
222
243
 
244
+ **A member's form for an entry** comes from its type: `const { form, save, errors } = useEntityForm({ schema: '@/course', uuid })` (no `uuid`: a new entry), held by kit's `useFormValues(form)` and drawn with the component that draws every `@std/form`; `save(values)`. Each control carries its field's kind and rules; `save` checks them first, and `errors` holds each problem by control path (`head.title` → `{ rule: 'max_length', max_length: 20 }`) for the foundation to word. A `File` in a `file` control is uploaded on save. List sections are written with `useEntityWriter`.
245
+
246
+ **A member's uploads:** `const { upload } = useUpload({ entity })`, then `await upload(input.files)` → `[{ url, assetId, assetExt, name, type, size, prepared, note? }]`; store `url` in the entry. Each file is prepared in the browser first, by the rule for uploaded media: a picture becomes a WebP when that makes it 10% smaller or turns it upright, and whatever is kept in its own format loses its location and camera data. Tell the member a `note`: `unconverted` (a TIFF or HEIC the browser couldn't convert) or `unreduced` (a video over the rule's bitrate). Upload through `useUpload`: it is what keeps a photo's location from going up with it.
247
+
223
248
  ## A backend on your machine
224
249
 
225
250
  ```yaml
@@ -394,6 +394,6 @@ Content-less containers appear as group nodes (`hasContent: false`); link with `
394
394
 
395
395
  **A heavy library used on demand.** `import('some-package')` where you use it keeps the package out of the page's first load and out of `dist/entry-ssr.js`, the file a host loads to render a page. A dynamic import of your own module only splits the browser's load: `entry-ssr.js` folds that module in, with every package it imports statically, and runs them when the file loads. So put the `import()` on the package, not on a component of yours that imports it. The build is green either way; the size of `entry-ssr.js` shows which you have.
396
396
 
397
- **`package.json` `uniweb` block** (all optional): `runtimePolicy` — a statement of how far past the recorded runtime version a host may move a site. The foundation's name and scope are `name` in `main.js` (`'@acme/marketing'`), not here; a name with no scope is unregistered, and the first `uniweb register` writes the scope in (from `--scope` or the Uniweb workspace you are logged in to). A foundation's own schemas register under the same scope (`@/article` → `@acme/article`). `uniweb.supports` is covered in the services guide.
397
+ **`package.json` `uniweb` block** (all optional): `runtimePolicy` — a statement of how far past the recorded runtime version a host may move a site. The foundation's name and scope are `name` in `main.js` (`'@acme/marketing'`), not here; a name with no scope is unregistered, and the first `uniweb register` writes the scope in (from `--scope` or the Uniweb workspace you are logged in to). A foundation's own schemas register under the same scope (`@/article` → `@acme/article`). `uniweb.supports` and `uniweb.requires` are covered in the services guide.
398
398
 
399
399
  **Runtime floor.** Your code externalizes `react`, `react-dom`, both JSX runtimes and `@uniweb/core`; the runtime supplies them. At build time the foundation records the `@uniweb/runtime` version it linked against into `dist/runtime-pin.json`, and `uniweb register` sends that version as its floor. `{ "uniweb": { "runtimePolicy": "exact" } }` asks for no movement past it, for a foundation that reaches into undocumented internals: it is recorded in that file and not sent at register, so whether anything acts on it is the host's to say. `@uniweb/runtime` arrives transitively through `@uniweb/build`; don't add it to the foundation's dependencies — bump `@uniweb/build` instead.
@@ -53,6 +53,8 @@ uniweb promote unschedule holiday.md # a draft again, its time kept
53
53
 
54
54
  - **`send` given the file writes it first,** as `post` does, so what goes out is what the file says. If the app changed the post since, it is refused and nothing goes out. `send <id>` sends the post as stored.
55
55
  - **`via`** names a network, and the post goes out through the site's account there. The first time, the CLI chooses it from your one account on that network. With several, give `via: { network: x, connection: <id> }`; the refusal lists them.
56
+ - **`uniweb promote use <network> posts`** chooses what on that account the site posts as, such as a page; `ads`, `search` and `listing` choose its ad account, property or listing. It lists the choices when there are several, and `--connection <id>` and `--target <id>` choose. A started campaign's account stays as it is.
57
+ - **What a network takes:** `post` says when a part is longer than its network takes, as that network counts it, the link included; most accounts would be refused. A post with more parts than its network takes (Facebook and LinkedIn take one) isn't sent until it has fewer.
56
58
  - **`page`** is a page of the site as pushed, so push a new page first. The live site must serve it in the post's language, or the send fails: publish first.
57
59
  - **A picture** given as a file is uploaded as one of the site's own, in its format. An `https:` address is kept as written, and so is one `show` printed.
58
60
  - **The words go out as written**, as plain text: Markdown formatting shows as typed.
@@ -97,7 +99,7 @@ uniweb promote resume holiday --yes
97
99
  - **A change made since then is never written over.** If the app or another run changed the draft, your write is refused and nothing is written. `uniweb promote show <id> > file` gives you the draft as it stands, to put your change into.
98
100
  - **Nothing is deleted by leaving it out.** An ad group or an ad the file doesn't hold is kept, and named. `uniweb promote delete <id>` deletes. A post's parts are its words, so the parts the file gives are the post's.
99
101
  - **A post that went out isn't edited or deleted.** To post again, drop `id` and `version` and make a new draft.
100
- - **Changing a scheduled post makes it a draft again,** its time kept, and `send` schedules it again.
102
+ - **Changing a scheduled post makes it a draft again,** its time kept, and `send` schedules it again. `send --at` moves the time and schedules in one step, so if it's refused the post stays as it was.
101
103
  - **An `<id>`** is the short one `status` shows, the file a draft was written from, or a campaign's name.
102
104
 
103
105
  ## The page it lands on
@@ -120,7 +122,12 @@ A campaign with `goal: conversions` optimizes for what its network hears back. T
120
122
 
121
123
  ## What each brought
122
124
 
123
- `uniweb promote status` shows what each running campaign has spent in each ad account, as the network last reported it, in that account's currency. A day it hasn't reported is unknown, not zero. The site's Analytics, in the app, shows its visits by where they came from. When you read them:
125
+ ```bash
126
+ uniweb promote results Holiday # a campaign: by day, by ad, and what it spent
127
+ uniweb promote results holiday.md --from 2026-12-01 # a post, from a day on (--to ends it)
128
+ ```
129
+
130
+ `results` gives what a post or a campaign brought, by UTC day, as the site's own analytics counts it: the arrivals, the page views and the conversions by name, matched by the tags in its links. It's the same count on every network, and a visitor two networks both claim counts once. A network's own clicks and impressions aren't in it. A campaign's comes per ad too, with what it spent in each ad account as the network last reported it, in that account's currency. A day the answer can't count is said to be unknown, not zero, and so are the arrivals that came with no ad's or post's tag. `uniweb promote status` shows each running campaign's spend. The site's Analytics, in the app, shows its visits by where they came from. When you read them:
124
131
 
125
132
  - judge by conversions, not clicks;
126
133
  - change one thing at a time;
@@ -134,6 +141,7 @@ A campaign with `goal: conversions` optimizes for what its network hears back. T
134
141
  | `status` | the site's Promote, and what needs the person |
135
142
  | `check <step>` · `check <route>` | one getting-found step (`sitemap`), or a page as a landing page |
136
143
  | `connect <network>` | the address where the person connects an account |
144
+ | `use <network> <posts\|ads\|search\|listing>` | what on that account the site goes out through; `--connection`, `--target` choose |
137
145
  | `post <file>` · `campaign <file>` | a draft, made or updated; `-` reads stdin |
138
146
  | `show <id>` | one post or campaign as its file holds it; its state goes to stderr |
139
147
  | `delete <id>` | a post, a campaign, an ad group or an ad |
@@ -141,5 +149,6 @@ A campaign with `goal: conversions` optimizes for what its network hears back. T
141
149
  | `unschedule <post>` | a scheduled post a draft again |
142
150
  | `start <campaign>` · `resume <campaign>` | spend, after saying what; `--yes` answers |
143
151
  | `pause <campaign>` | wherever it runs |
152
+ | `results <post\|campaign> [--from <day>] [--to <day>]` | what it brought by day, as the site's own analytics counts it |
144
153
 
145
154
  All of them take `--json`; `--site <uuid>` for a site this project isn't synced to; `--org @x` or `--personal` for the workspace. A time carries its offset: `2026-11-24T09:00-05:00`.
@@ -36,7 +36,13 @@ An entry is `true`, `false`, an address (a string, or `endpoint:` in a map), or
36
36
  { "uniweb": { "supports": ["search", "submit"] } }
37
37
  ```
38
38
 
39
- A service only does something if the foundation renders against it, and a host can't otherwise know. The build derives the set from what the bundle reaches (`resolveService(website, 'search')`, `isSearchEnabled()`), so an undeclared foundation still publishes an accurate set; what you write is a supplement (union), and only needed for a service reached through a computed name (`resolveService(website, name)` — the build warns). `[]` means none, proven by the build; absent means unknown. Never list `tracking`: the runtime reports for every foundation, so the build drops the name with a warning. `uniweb doctor` compares declared with found.
39
+ A service only does something if the foundation renders against it, and a host can't otherwise know. The build derives the set from what the bundle reaches (`resolveService(website, 'search')`, `isSearchEnabled()`), so an undeclared foundation still publishes an accurate set; what you write is a supplement (union), and only needed for a service reached through a computed name (`resolveService(website, name)` — the build warns). A published set is complete: when the build meets a computed name and you declared nothing, it publishes no set (unknown) rather than a partial one, and says what to list. `[]` means none, proven by the build; absent means unknown.
40
+
41
+ ```json
42
+ { "uniweb": { "requires": ["backend"] } }
43
+ ```
44
+
45
+ `requires` names the services the foundation cannot work without — sign-in and purchases for a course site, say — as opposed to ones it uses when they are on. The build cannot tell the two apart, so only you can declare it; each name joins `supports`, and the build warns if no code reaches it. Uniweb hosting keeps a required service on for every site using the foundation, so its owner is never offered a switch that breaks the site. A required service can still be missing for a moment (while it starts for a new site, say), so a section that calls it shows its own "not available yet" state rather than failing. Never list `tracking`: the runtime reports for every foundation, so the build drops the name with a warning. `uniweb doctor` compares declared with found.
40
46
 
41
47
  ## Search
42
48
 
@@ -1049,20 +1049,21 @@ export class BackendClient {
1049
1049
 
1050
1050
  /**
1051
1051
  * POST /dev/site/promotion/{site}/posts/{post}/{act} — a post's doors: `publish` (now),
1052
- * `schedule` (at its `send_at`) and `unschedule` (a draft again, its `send_at` kept). Each
1053
- * answers `{ delivery }`; `unschedule`'s is `null` once a draft. Publishing and scheduling
1054
- * take `admin` on the site and `edit` on the account it goes out through; unscheduling takes
1055
- * `edit` on the site.
1052
+ * `schedule` (at its `send_at`, or at the `send_at` the body gives, in one act refused whole)
1053
+ * and `unschedule` (a draft again, its `send_at` kept). Each answers `{ delivery }`;
1054
+ * `unschedule`'s is `null` once a draft. Publishing and scheduling take `admin` on the site and
1055
+ * `edit` on the account it goes out through; unscheduling takes `edit` on the site.
1056
1056
  *
1057
1057
  * @param {string} siteUuid
1058
1058
  * @param {string} postUuid
1059
1059
  * @param {'publish'|'schedule'|'unschedule'} act
1060
+ * @param {{ send_at: string } | null} [body] - `schedule`'s new time
1060
1061
  * @returns {Promise<Response>}
1061
1062
  */
1062
- async postAction(siteUuid, postUuid, act) {
1063
+ async postAction(siteUuid, postUuid, act, body = null) {
1063
1064
  return this.request(
1064
1065
  `/dev/site/promotion/${encodeURIComponent(siteUuid)}/posts/${encodeURIComponent(postUuid)}/${act}`,
1065
- { method: 'POST' }
1066
+ { method: 'POST', ...(body ? { body: JSON.stringify(body) } : {}) }
1066
1067
  )
1067
1068
  }
1068
1069
 
@@ -1099,6 +1100,30 @@ export class BackendClient {
1099
1100
  )
1100
1101
  }
1101
1102
 
1103
+ /**
1104
+ * GET /dev/site/promotion/{site}/{posts|campaigns}/{uuid}/results?from=&to= — `{ results }`:
1105
+ * what a post or a campaign brought by UTC day, as the site's own analytics counts it, matched
1106
+ * by the tags in its links: `days` of `{ day, arrivals, views, conversions }`, `untold`,
1107
+ * `range`, `measured_from`, `cut`, `capped`; a campaign's also `ad_groups`, `ads` and `spend`.
1108
+ * `from` and `to` are UTC days, inclusive, both optional. Takes `edit` on the site; `402` for a
1109
+ * site without Analytics, `503` where the backend reaches no analytics view.
1110
+ *
1111
+ * @param {string} siteUuid
1112
+ * @param {'posts'|'campaigns'} kind
1113
+ * @param {string} uuid
1114
+ * @param {{ from?: string|null, to?: string|null }} [days]
1115
+ * @returns {Promise<Response>}
1116
+ */
1117
+ async promotionResults(siteUuid, kind, uuid, { from = null, to = null } = {}) {
1118
+ const query = {}
1119
+ if (from) query.from = from
1120
+ if (to) query.to = to
1121
+ return this.request(
1122
+ `/dev/site/promotion/${encodeURIComponent(siteUuid)}/${kind}/${encodeURIComponent(uuid)}/results`,
1123
+ { query }
1124
+ )
1125
+ }
1126
+
1102
1127
  /**
1103
1128
  * GET /dev/connections — `{ connections: [{ uuid, owner?, unit?, card }] }`: the network
1104
1129
  * connections the caller reaches in the workspace the request names. A card holds the
@@ -1110,6 +1135,20 @@ export class BackendClient {
1110
1135
  return this.request('/dev/connections')
1111
1136
  }
1112
1137
 
1138
+ /**
1139
+ * GET /dev/connections/{uuid}/reach?use= — `{ reach: [{ id, name }] }`: what the connection
1140
+ * reaches at its network for one use (`posts`, `ads`, `search`, `listing`), read from the
1141
+ * network as asked. Each is the shape a `networks` item's `target` holds. An empty list is an
1142
+ * account that reaches nothing for that use yet. Takes `read` on the connection.
1143
+ *
1144
+ * @param {string} connectionUuid
1145
+ * @param {string} use
1146
+ * @returns {Promise<Response>}
1147
+ */
1148
+ async connectionReach(connectionUuid, use) {
1149
+ return this.request(`/dev/connections/${encodeURIComponent(connectionUuid)}/reach`, { query: { use } })
1150
+ }
1151
+
1113
1152
  /**
1114
1153
  * POST /dev/connections/consent — `{ network, return_to? }` → `{ address }`, the network's
1115
1154
  * consent page. The browser that finishes it must be signed in to the app as the same
@@ -79,15 +79,23 @@ function referencedFirst(libraries, schemas, mappings = {}) {
79
79
  return out
80
80
  }
81
81
 
82
- /** The types a mapping names, as its `_mappings` entry holds them (in full): its `model` and its `follow` lines'. */
82
+ /**
83
+ * The types a mapping names, as its `_mappings` entry holds them (in full) or as written: its `model`
84
+ * and its `follow` lines', and the same in each of a `set`'s `parts`.
85
+ */
83
86
  export function typesNamedBy(mapping) {
84
87
  if (!mapping || typeof mapping !== 'object') return []
85
88
  const out = []
86
- if (typeof mapping.model === 'string') out.push(mapping.model)
87
- for (const line of Array.isArray(mapping.follow) ? mapping.follow : []) {
88
- if (!line || typeof line !== 'object') continue
89
- for (const spec of Object.values(line)) if (spec && typeof spec.model === 'string') out.push(spec.model)
89
+ const rulesOf = (rules) => {
90
+ if (!rules || typeof rules !== 'object') return
91
+ if (typeof rules.model === 'string') out.push(rules.model)
92
+ for (const line of Array.isArray(rules.follow) ? rules.follow : []) {
93
+ if (!line || typeof line !== 'object') continue
94
+ for (const spec of Object.values(line)) if (spec && typeof spec.model === 'string') out.push(spec.model)
95
+ }
90
96
  }
97
+ rulesOf(mapping)
98
+ for (const part of Array.isArray(mapping.parts) ? mapping.parts : []) rulesOf(part)
91
99
  return out
92
100
  }
93
101
 
@@ -183,6 +183,10 @@ export const REASONS = {
183
183
  connection_not_permitted: 'whoever scheduled it may no longer post through its account',
184
184
  network_not_offered: 'this backend does not offer that network',
185
185
  network_refused: 'the network refused it',
186
+ too_many_parts: 'it has more parts than its network takes in a post',
187
+ send_at_not_ahead: 'its time is not ahead of now: give one ahead with --at, or send it now with --now',
188
+ send_at_invalid: 'its time is not a date-time with its offset, such as 2026-11-24T09:00-05:00',
189
+ post_published: 'it went out already, so it is not sent again: a new post is a new draft',
186
190
  promote_off: 'the site has no Promote: it comes with the site\'s Analytics, which the person turns on in the app',
187
191
  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
192
  }
@@ -430,6 +434,146 @@ export function picturesOf(draft) {
430
434
  return [...new Set(out)]
431
435
  }
432
436
 
437
+ // ── What a network takes in a post ─────────────────────────────────────────────────
438
+
439
+ /** A network as a person names it. */
440
+ export const NETWORK_NAMES = { x: 'X', linkedin: 'LinkedIn', facebook: 'Facebook', google: 'Google', bing: 'Bing' }
441
+
442
+ /** The code points X counts as one; any other counts two (X's own ranges). */
443
+ const X_LIGHT = [[0, 4351], [8192, 8205], [8208, 8223], [8242, 8247]]
444
+ /** What X counts an address as, wherever it stands. */
445
+ const X_URL = 23
446
+ /** A grapheme X counts as one emoji, sequences included: a pictograph, a keycap, a flag. */
447
+ const EMOJI = /\p{Extended_Pictographic}|⃣|\p{Regional_Indicator}/u
448
+
449
+ /**
450
+ * A text's length as its network counts it. As X counts (`counting: "x"`): NFC first, each
451
+ * address 23, each emoji 2, a code point in X's light ranges 1 and any other 2. Otherwise, by its
452
+ * characters.
453
+ */
454
+ export function countedLength(text, counting) {
455
+ const t = String(text ?? '').normalize('NFC')
456
+ if (counting !== 'x') return Array.from(t).length
457
+ let n = 0
458
+ const rest = t.replace(/https?:\/\/\S+/gi, () => {
459
+ n += X_URL
460
+ return ''
461
+ })
462
+ for (const { segment } of new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(rest)) {
463
+ if (EMOJI.test(segment)) {
464
+ n += 2
465
+ continue
466
+ }
467
+ for (const ch of segment) {
468
+ const cp = ch.codePointAt(0)
469
+ n += X_LIGHT.some(([a, b]) => cp >= a && cp <= b) ? 1 : 2
470
+ }
471
+ }
472
+ return n
473
+ }
474
+
475
+ /**
476
+ * What a post's network takes, as `/dev/config` tells it (`promote.limits[network].posts`):
477
+ * `characters` a part, counted as `counting` says; `link`, what the post's link counts in its
478
+ * first part; `parts`, how many parts it takes (none told: a thread). Null when none is told.
479
+ */
480
+ export function postLimits(config, network) {
481
+ const limits = config?.promote?.limits?.[network]?.posts
482
+ return isPlainObject(limits) ? limits : null
483
+ }
484
+
485
+ /**
486
+ * Where a post asks more than its network takes, in words: more parts, which the backend refuses
487
+ * before anything goes out, and a part longer than the network takes, which the network refuses
488
+ * for most accounts (some post longer), so it is a note.
489
+ *
490
+ * @param {{ text?: string }[]} parts - the post's parts, in order
491
+ * @param {object|null} limits - `postLimits`
492
+ * @param {{ network: string, link: boolean }} post - its network, and whether it carries a link
493
+ * @returns {{ parts: string|null, lengths: string[] }}
494
+ */
495
+ export function overLimits(parts, limits, { network, link }) {
496
+ const out = { parts: null, lengths: [] }
497
+ if (!limits) return out
498
+ const name = NETWORK_NAMES[network] ?? network
499
+ if (Number.isInteger(limits.parts) && parts.length > limits.parts) {
500
+ const takes = limits.parts === 1 ? 'one part' : `${limits.parts} parts`
501
+ out.parts = `${name} takes ${takes} in a post, and this one has ${parts.length}: make it ${limits.parts === 1 ? 'one' : limits.parts}.`
502
+ }
503
+ if (Number.isInteger(limits.characters)) {
504
+ parts.forEach((p, i) => {
505
+ const withLink = i === 0 && link && Number.isInteger(limits.link)
506
+ const n = countedLength(p.text, limits.counting) + (withLink ? limits.link : 0)
507
+ if (n <= limits.characters) return
508
+ out.lengths.push(
509
+ `${parts.length === 1 ? 'It' : `Part ${i + 1}`} is ${n} characters${limits.counting === 'x' ? ' as X counts them' : ''}` +
510
+ `${withLink ? `, its link's ${limits.link} among them` : ''}, and ${name} takes ${limits.characters}: most accounts there would be refused.`
511
+ )
512
+ })
513
+ }
514
+ return out
515
+ }
516
+
517
+ // ── What a post or a campaign brought ──────────────────────────────────────────────
518
+
519
+ /** Day rows summed: arrivals, views, and each conversion by its name. */
520
+ export function resultTotals(days) {
521
+ const out = { arrivals: 0, views: 0, conversions: {} }
522
+ for (const d of Array.isArray(days) ? days : []) {
523
+ if (Number.isFinite(d?.arrivals)) out.arrivals += d.arrivals
524
+ if (Number.isFinite(d?.views)) out.views += d.views
525
+ for (const [name, n] of Object.entries(isPlainObject(d?.conversions) ? d.conversions : {})) {
526
+ if (Number.isFinite(n)) out.conversions[name] = (out.conversions[name] ?? 0) + n
527
+ }
528
+ }
529
+ return out
530
+ }
531
+
532
+ /** A day row, or a total, in words: `3 arrivals · 5 views · signup 1`. */
533
+ export function resultWords(row) {
534
+ const count = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`
535
+ const conversions = Object.entries(isPlainObject(row?.conversions) ? row.conversions : {})
536
+ .filter(([, n]) => n)
537
+ .map(([name, n]) => `${name} ${n}`)
538
+ return [count(row?.arrivals ?? 0, 'arrival'), count(row?.views ?? 0, 'view'), ...conversions].join(' · ')
539
+ }
540
+
541
+ /**
542
+ * What a results answer's days can be read as, in words: from when they are counted, whether
543
+ * some may be missing, and what came with no ad's or post's tag. The answer's own fields:
544
+ * `measured_from` (a day, or null when the site's analytics hold none of its tags), `cut` and
545
+ * `capped` (booleans) and `untold` (day rows, only on days that have them).
546
+ *
547
+ * @param {object} results
548
+ * @param {{ kind: 'post'|'campaign', network?: string|null }} what
549
+ */
550
+ export function resultNotes(results, { kind, network = null }) {
551
+ const notes = []
552
+ const from = results?.range?.from ?? null
553
+ if (results?.measured_from === null) {
554
+ notes.push('The site\'s analytics hold nothing with its tags in the days they keep, so there is nothing to count yet.')
555
+ } else if (typeof results?.measured_from === 'string' && from && results.measured_from > from) {
556
+ notes.push(`Counted from ${results.measured_from}, when the site's analytics first held its tags: a day before it is unknown, not zero.`)
557
+ }
558
+ if (results?.cut === true) {
559
+ notes.push('Some values may be missing, since the site\'s analytics kept as many as they keep for these days: a day not listed is unknown, not zero. A shorter window (--from, --to) reads them all.')
560
+ }
561
+ if (results?.capped === true) {
562
+ notes.push('A day held more than the site\'s analytics keep in one, so some arrivals sit in no campaign: these counts are the least it brought.')
563
+ }
564
+ const untold = Array.isArray(results?.untold) ? results.untold : []
565
+ const sum = resultTotals(untold)
566
+ if (sum.arrivals || sum.views) {
567
+ const on = untold.map((d) => d.day).filter(Boolean).join(', ')
568
+ notes.push(
569
+ kind === 'campaign'
570
+ ? `${resultWords(sum)} came with the campaign's tag but no ad's (${on}), as from a page that sends no referrer: they count toward no ad.`
571
+ : `${resultWords(sum)} came from ${NETWORK_NAMES[network] ?? network ?? 'its network'}'s posts with no post's tag (${on}): no post can claim them.`
572
+ )
573
+ }
574
+ return notes
575
+ }
576
+
433
577
  /** Whether a picture is an address already, kept as written, rather than a file to upload. */
434
578
  export function isAddress(picture) {
435
579
  return /^https?:\/\//i.test(picture)
@@ -538,8 +538,9 @@ export async function checkFoundationSupports({
538
538
  } catch {
539
539
  return // unreadable or malformed build output — not this check's to report
540
540
  }
541
- // Absent means the build derived nothing and saw a computed name, so it
542
- // reported UNKNOWN. There is no gap to name.
541
+ // Absent means the build saw a computed name with nothing declared, so it
542
+ // reported UNKNOWN rather than a partial set (it publishes only a complete
543
+ // one) and named what it found itself. There is no list here to compare.
543
544
  if (!Array.isArray(derived) || derived.length === 0) return
544
545
 
545
546
  const declared = pkg?.uniweb?.supports
@@ -5,6 +5,7 @@
5
5
  * uniweb promote status [--json] the site's Promote on one screen, and what needs a person
6
6
  * uniweb promote check <step> [--json] check one getting-found step (`sitemap`, say)
7
7
  * uniweb promote connect <network> the address where a person connects an account
8
+ * uniweb promote use <network> <use> the account, and the page or ad account, it goes out through
8
9
  * uniweb promote post <file> make a post's draft, or update the one the file names
9
10
  * uniweb promote campaign <file> the same for a campaign, its ad groups and ads
10
11
  * uniweb promote show <id> [--json] one post or campaign, as a draft holds it
@@ -13,6 +14,7 @@
13
14
  * uniweb promote unschedule <post> a scheduled post a draft again, its time kept
14
15
  * uniweb promote start | resume <campaign> [--yes] spend: say what, ask, then start
15
16
  * uniweb promote pause <campaign> pause it wherever it runs
17
+ * uniweb promote results <post|campaign> what it brought, by day, as the site's own analytics counts it
16
18
  *
17
19
  * The site is the one this project is synced to on that backend, or `--site <uuid>`. The
18
20
  * workspace is `--org @x` or `--personal`, else the login's — as for every site request.
@@ -59,7 +61,13 @@ import {
59
61
  indexPromotion,
60
62
  isAddress,
61
63
  kindOf,
64
+ NETWORK_NAMES,
65
+ overLimits,
62
66
  pageRoute,
67
+ postLimits,
68
+ resultNotes,
69
+ resultTotals,
70
+ resultWords,
63
71
  parseDraft,
64
72
  picturesOf,
65
73
  planCampaign,
@@ -107,6 +115,9 @@ const USAGE = [
107
115
  ' and what needs a person',
108
116
  ' check <step> Check one getting-found step, e.g. uniweb promote check sitemap',
109
117
  ' connect <network> The address where a person connects an account at a network',
118
+ ' use <network> <use> The account and the page, ad account, property or listing the site',
119
+ ' goes out through for posts, ads, search or listing; it lists the',
120
+ ' choices, and --connection <id> and --target <id> choose',
110
121
  ' post <file> Make a post\'s draft (Markdown, YAML or JSON), or update the one',
111
122
  ' the file names; the file gets its id and version back',
112
123
  ' campaign <file> The same for a campaign (YAML or JSON), its ad groups and ads',
@@ -120,6 +131,9 @@ const USAGE = [
120
131
  ' asks; --yes answers for you',
121
132
  ' resume <campaign> Resume it where it was paused, the same way',
122
133
  ' pause <campaign> Pause it wherever it runs',
134
+ ' results <post|campaign> What it brought by day, as the site\'s own analytics counts it:',
135
+ ' arrivals, views and conversions, a campaign\'s by ad and with its',
136
+ ' spend; --from <day> and --to <day> choose the days',
123
137
  '',
124
138
  '--json gives any command\'s answer as JSON. An <id> is the one a command shows, a file',
125
139
  'a draft was written from, or a campaign\'s name.',
@@ -131,7 +145,7 @@ const USAGE = [
131
145
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
132
146
 
133
147
  /** Flags that take a value, so the value is not read as an argument. */
134
- const VALUED = new Set(['--org', '--site', '--at'])
148
+ const VALUED = new Set(['--org', '--site', '--at', '--connection', '--target', '--from', '--to'])
135
149
 
136
150
  /** The arguments that are not flags, skipping the values of the flags that take one. */
137
151
  function positionals(args) {
@@ -213,10 +227,11 @@ async function sayRefusal(res, { site, origin, what, index = null, notFound = nu
213
227
  say.err(`${REASONS.feature_not_subscribed}.`)
214
228
  } else if (res.status === 403 && body?.op === 'admin') {
215
229
  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
230
  } else if (res.status === 403 && forbidden) {
219
231
  say.err(forbidden)
232
+ } else if (res.status === 403 && body?.op === 'edit' && body?.target && !String(body.target).includes(site)) {
233
+ // A refusal names what it refused (`target`): the site itself, or the account a post or a campaign goes out through.
234
+ 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.`)
220
235
  } else if (res.status === 403) {
221
236
  say.err(`You may not ${what} on this site${body?.op ? ` (it takes ${body.op})` : ''}.`)
222
237
  } else if (res.status === 404) {
@@ -227,6 +242,11 @@ async function sayRefusal(res, { site, origin, what, index = null, notFound = nu
227
242
  `${name ? `“${name}”` : 'The campaign'} has started in an ad account, and what runs there is fixed, so the write is refused — nothing changed. ` +
228
243
  'Add an ad account to its `via`, or draft a new campaign.'
229
244
  )
245
+ } else if (res.status === 400 && reason === 'too_many_parts') {
246
+ const takes = body?.parts === 1 ? 'one part' : `${body?.parts ?? 'fewer'} parts`
247
+ say.err(`${NETWORK_NAMES[body?.network] ?? body?.network ?? 'Its network'} takes ${takes} in a post, and this one has more, so nothing went out. Make it ${body?.parts === 1 ? 'one' : (body?.parts ?? 'fewer')}.`)
248
+ } else if (res.status === 400 && reason && REASONS[reason]) {
249
+ say.err(`Refused, nothing changed: ${REASONS[reason]}.`)
230
250
  } else if (res.status === 409) {
231
251
  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>`)
232
252
  } else {
@@ -723,6 +743,201 @@ async function begin(args, command, verb) {
723
743
  return { client: conn.client, workspace: conn.workspace, site }
724
744
  }
725
745
 
746
+ /** What a site goes out through a network for. */
747
+ const USES = ['posts', 'ads', 'search', 'listing']
748
+
749
+ /**
750
+ * `uniweb promote use <network> <posts|ads|search|listing>` — the account the site goes out
751
+ * through on a network for one use, and what at that account: the profile or page it posts as,
752
+ * the ad account its ads run in, a property, a listing. It lists the choices when there is more
753
+ * than one; `--connection <id>` and `--target <id>` choose. It makes or updates the site's one
754
+ * `networks` item for that network and use.
755
+ */
756
+ async function useAccount(args) {
757
+ const json = args.includes('--json')
758
+ const [, network, use] = positionals(args)
759
+ if (!network || !USES.includes(use)) {
760
+ say.err(`Name the network and what for: uniweb promote use <network> <${USES.join('|')}>`)
761
+ return { exitCode: 2 }
762
+ }
763
+ const at = await begin(args, 'Choosing an account', `use ${network} ${use}`)
764
+ if (!at.client) return at
765
+ const { client, site } = at
766
+ const index = await readIndex(client, site)
767
+ if (!index) return { exitCode: 1 }
768
+ const connections = await listedConnections(client)
769
+ if (connections === null) {
770
+ say.err(`Could not list the accounts you can use on ${client.origin}.`)
771
+ return { exitCode: 1 }
772
+ }
773
+ const name = NETWORK_NAMES[network] ?? network
774
+ const mine = connections.filter((k) => k.card?.network === network)
775
+ if (!mine.length) {
776
+ say.err(`You have no ${name} account to use. Its person connects one, in a browser: uniweb promote connect ${network}`)
777
+ return { exitCode: 2 }
778
+ }
779
+ const item = index.top('networks').find((n) => n.data?.network === network && n.data?.use === use) ?? null
780
+ const current = connectionOf(item?.data?.connection).uuid
781
+ const kIds = shortIds(mine.map((k) => k.uuid))
782
+ const named = (k) => `“${k.card?.name || k.card?.handle || k.uuid}”`
783
+ const choices = (lines, how) => {
784
+ if (json) console.log(JSON.stringify({ backend: client.origin, site, network, use, choose: how, ...lines }))
785
+ return { exitCode: 2 }
786
+ }
787
+
788
+ // The account: the one named, else the only one, else the one the site goes out through now.
789
+ const wantConnection = flagValue(args, '--connection')
790
+ const conn = wantConnection
791
+ ? mine.find((k) => idMatches(k.uuid, wantConnection))
792
+ : mine.length === 1 ? mine[0] : mine.find((k) => k.uuid === current)
793
+ if (!conn) {
794
+ if (!json) {
795
+ say.err(wantConnection ? `None of your ${name} accounts is ${wantConnection}. Choose one:` : `You have ${mine.length} ${name} accounts. Choose one:`)
796
+ for (const k of mine) say.dim(`${kIds.get(k.uuid)} ${named(k)}${k.card?.state && k.card.state !== 'connected' ? ` (${k.card.state})` : ''}`)
797
+ say.dim(`uniweb promote use ${network} ${use} --connection <id>`)
798
+ }
799
+ return choices({ connections: mine.map((k) => ({ uuid: k.uuid, short: kIds.get(k.uuid), card: k.card ?? null })) }, '--connection')
800
+ }
801
+
802
+ // What that account reaches for this use, read from the network as asked.
803
+ const res = await client.connectionReach(conn.uuid, use)
804
+ if (!res.ok) {
805
+ const body = await res.clone().json().catch(() => null)
806
+ if (res.status === 400 && body?.reason === 'use_not_offered') say.err(`${name} offers no ${use} to go out through.`)
807
+ else if (res.status === 409 && body?.reason === 'connection_cannot_act') say.err(`${named(conn)} can't act now: ${reasonWords(body?.why)}.`)
808
+ else if (res.status === 502) say.err(`${name} refused to say what ${named(conn)} reaches${body?.detail ? `: ${body.detail}` : ''}.`)
809
+ else if (res.status === 404) say.err(`${named(conn)} is not shared with you to read what it reaches: ask whoever connected it.`)
810
+ else await sayRefusal(res, { site, origin: client.origin, what: 'read what that account reaches', index })
811
+ return { exitCode: res.status === 400 ? 2 : 1 }
812
+ }
813
+ const reach = ((await res.json().catch(() => null))?.reach ?? []).filter((t) => t && typeof t.id === 'string')
814
+ if (!reach.length) {
815
+ say.err(`${named(conn)} reaches nothing on ${name} for ${use} yet. Make it there first (a page, an ad account), then run this again.`)
816
+ return { exitCode: 1 }
817
+ }
818
+ const wantTarget = flagValue(args, '--target')
819
+ const target = wantTarget
820
+ ? reach.find((t) => t.id === wantTarget || t.name === wantTarget)
821
+ : reach.length === 1 ? reach[0] : reach.find((t) => conn.uuid === current && t.id === item?.data?.target?.id)
822
+ if (!target) {
823
+ if (!json) {
824
+ say.err(`${wantTarget ? `${named(conn)} reaches no ${wantTarget} for ${use}.` : `${named(conn)} reaches ${reach.length} for ${use}.`} Choose one:`)
825
+ for (const t of reach) say.dim(`${t.id} “${t.name ?? t.id}”`)
826
+ say.dim(`uniweb promote use ${network} ${use}${mine.length > 1 ? ` --connection ${kIds.get(conn.uuid)}` : ''} --target <id>`)
827
+ }
828
+ return choices({ connection: conn.uuid, reach }, '--target')
829
+ }
830
+
831
+ // The site's one item for this network and use, made or pointed at what was chosen.
832
+ const same = Boolean(item) && current === conn.uuid && item.data?.target?.id === target.id
833
+ let uuid = item?.uuid ?? null
834
+ if (!same) {
835
+ const data = { ...(item?.data ?? {}), network, use, connection: conn.uuid, target: { id: target.id, name: target.name ?? target.id } }
836
+ uuid = uuid ?? mintUuidV7()
837
+ const op = item
838
+ ? { kind: 'update', uuid, data, if_unmodified_since: item.updated_at }
839
+ : { kind: 'create', section: 'networks', uuid, data }
840
+ const w = await client.writePromotionItems(site, [op])
841
+ if (!w.ok) {
842
+ const body = await w.clone().json().catch(() => null)
843
+ if (w.status === 409 && body?.reason === 'campaign_started') {
844
+ const started = index.byUuid.get(body?.campaign)?.data?.name
845
+ say.err(`${started ? `“${started}”` : 'A campaign'} has started through the site's ${name} ${use} account, and a started campaign's account stays as it is, paused or not. Nothing changed.`)
846
+ } else {
847
+ await sayRefusal(w, { site, origin: client.origin, what: 'choose its accounts', index })
848
+ }
849
+ return { exitCode: 1 }
850
+ }
851
+ }
852
+ if (json) {
853
+ console.log(JSON.stringify({ backend: client.origin, site, network, use, item: uuid, connection: conn.uuid, target, changed: !same }))
854
+ return { exitCode: 0 }
855
+ }
856
+ say.ok(`${same ? 'Already so: the' : 'The'} site's ${use} on ${name} go out through ${named(conn)}, as “${target.name ?? target.id}”.`)
857
+ const others = reach.filter((t) => t.id !== target.id)
858
+ if (others.length) say.dim(`It also reaches ${others.map((t) => `“${t.name ?? t.id}” (${t.id})`).join(', ')}: --target <id> chooses one.`)
859
+ return { exitCode: 0 }
860
+ }
861
+
862
+ /** A UTC day, as `--from` and `--to` take one. */
863
+ const DAY = /^\d{4}-\d{2}-\d{2}$/
864
+
865
+ /**
866
+ * `uniweb promote results <post|campaign> [--from <day>] [--to <day>]` — what a post or a
867
+ * campaign brought, by UTC day, as the site's own analytics counts it: arrivals, views and
868
+ * conversions by name, matched by the tags in its links. Never a network's own count, which
869
+ * credits itself. A campaign's also comes per ad, with what it spent.
870
+ */
871
+ async function results(args) {
872
+ const json = args.includes('--json')
873
+ const arg = positionals(args)[1]
874
+ const from = flagValue(args, '--from')
875
+ const to = flagValue(args, '--to')
876
+ if (!arg) {
877
+ say.err('Name the post or the campaign: uniweb promote results <id> [--from <day>] [--to <day>]')
878
+ return { exitCode: 2 }
879
+ }
880
+ for (const [flag, value] of [['--from', from], ['--to', to]]) {
881
+ if (args.includes(flag) && !DAY.test(value ?? '')) {
882
+ say.err(`\`${flag}\` takes a UTC day, such as 2026-12-01.`)
883
+ return { exitCode: 2 }
884
+ }
885
+ }
886
+ const at = await begin(args, 'Reading what it brought', `results ${arg}`)
887
+ if (!at.client) return at
888
+ const { client, site } = at
889
+ const index = await readIndex(client, site)
890
+ if (!index) return { exitCode: 1 }
891
+ const item = pick(index, arg, ['post', 'campaign'])
892
+ if (!item) return { exitCode: 2 }
893
+ const kind = item.section === 'posts' ? 'post' : 'campaign'
894
+ const res = await client.promotionResults(site, kind === 'post' ? 'posts' : 'campaigns', item.uuid, { from, to })
895
+ if (!res.ok) {
896
+ if (res.status === 503) say.err(`${client.origin} reaches no analytics view, so it can't count what this brought. A backend that serves the site counts it; a local one may not.`)
897
+ else await sayRefusal(res, { site, origin: client.origin, what: 'read what it brought', index, forbidden: VIEW_ONLY })
898
+ return { exitCode: 1 }
899
+ }
900
+ const r = (await res.json().catch(() => null))?.results ?? null
901
+ const ids = shortIds(index.items.map((i) => i.uuid))
902
+ if (json) {
903
+ console.log(JSON.stringify({ backend: client.origin, site, kind, id: item.uuid, short: ids.get(item.uuid), results: r }))
904
+ return { exitCode: r ? 0 : 1 }
905
+ }
906
+ if (!r) {
907
+ say.err('The backend answered with no results.')
908
+ return { exitCode: 1 }
909
+ }
910
+ const network = kind === 'post' ? (index.byUuid.get(item.data?.via)?.data?.network ?? null) : null
911
+ console.log(
912
+ `${c.bold}What ${kind} ${labelOf(index, item)} (${ids.get(item.uuid)}) brought${c.reset}` +
913
+ ` ${c.dim}— ${r.range?.from ?? '?'} to ${r.range?.to ?? '?'}, as the site's own analytics counts it${c.reset}`
914
+ )
915
+ const days = Array.isArray(r.days) ? r.days : []
916
+ for (const d of days) console.log(` ${d.day} ${resultWords(d)}`)
917
+ if (days.length > 1) console.log(` ${c.bold}In all${c.reset} ${resultWords(resultTotals(days))}`)
918
+ if (kind === 'campaign') {
919
+ const ads = Array.isArray(r.ads) ? r.ads : []
920
+ if (ads.length) console.log(` ${c.bold}By ad${c.reset}`)
921
+ for (const a of ads) {
922
+ const ad = index.byUuid.get(a.ad)
923
+ const group = index.byUuid.get(a.ad_group)?.data?.name
924
+ console.log(` ${c.cyan}${ids.get(a.ad) ?? a.ad}${c.reset} ${ad ? labelOf(index, ad) : '(an ad no longer here)'}${group ? ` in “${group}”` : ''}: ${resultWords(resultTotals(a.days))}`)
925
+ }
926
+ const rows = Array.isArray(r.spend) ? r.spend : []
927
+ const spent = sumSpend(rows)
928
+ const reported = new Set(rows.map((s) => s.day).filter(Boolean)).size
929
+ console.log(
930
+ ` ${c.bold}Spent${c.reset} ` +
931
+ (Object.keys(spent).length
932
+ ? `${Object.entries(spent).map(([cur, amount]) => `${amount} ${cur}`).join(' + ')}, on the ${reported} day${reported === 1 ? '' : 's'} the network reported`
933
+ : 'nothing reported yet')
934
+ )
935
+ }
936
+ for (const note of resultNotes(r, { kind, network })) say.dim(note)
937
+ say.dim('These are the site\'s own counts of who arrived, not a network\'s clicks or impressions.')
938
+ return { exitCode: 0 }
939
+ }
940
+
726
941
  /** The site's Promote, read fresh and indexed — or null, the refusal said. */
727
942
  async function readIndex(client, site) {
728
943
  const res = await client.readPromotion(site)
@@ -746,6 +961,17 @@ async function readPages(client, site) {
746
961
  }
747
962
  }
748
963
 
964
+ /**
965
+ * Where a post as stored asks more than its network takes (`overLimits`), by the limits this
966
+ * backend tells; none when it tells none.
967
+ */
968
+ async function limitsOf(client, index, post) {
969
+ const network = index.byUuid.get(post?.data?.via)?.data?.network
970
+ const config = network ? await client.discover().catch(() => null) : null
971
+ const parts = index.children('posts/parts', post.uuid).map((p) => p.data ?? {})
972
+ return overLimits(parts, postLimits(config, network), { network, link: Boolean(post.data?.page) })
973
+ }
974
+
749
975
  /** The caller's connections — null when they could not be listed. */
750
976
  async function listedConnections(client) {
751
977
  const res = await client.listConnections().catch(() => null)
@@ -1104,6 +1330,8 @@ async function writeDraft(args, kind) {
1104
1330
  const ids = shortIds(after.items.map((i) => i.uuid))
1105
1331
  const item = after.byUuid.get(plan.uuid)
1106
1332
  const id = ids.get(plan.uuid) ?? plan.uuid
1333
+ // What its network takes: more parts is refused when it goes out, a long part only noted.
1334
+ const over = kind === 'post' && item ? await limitsOf(client, after, item) : { parts: null, lengths: [] }
1107
1335
  if (json) {
1108
1336
  console.log(JSON.stringify({
1109
1337
  backend: client.origin,
@@ -1115,7 +1343,8 @@ async function writeDraft(args, kind) {
1115
1343
  made: !draft.id,
1116
1344
  writes: ops.length,
1117
1345
  file: input.file ? input.shown : null,
1118
- kept: (plan.kept ?? []).map((k) => ({ ...k, short: ids.get(k.uuid) }))
1346
+ kept: (plan.kept ?? []).map((k) => ({ ...k, short: ids.get(k.uuid) })),
1347
+ ...(kind === 'post' ? { limits: over } : {})
1119
1348
  }))
1120
1349
  return { exitCode: 0 }
1121
1350
  }
@@ -1144,6 +1373,8 @@ async function writeDraft(args, kind) {
1144
1373
  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.`)
1145
1374
  }
1146
1375
  }
1376
+ if (over.parts) say.warn(`${over.parts} Until then it can't be sent.`)
1377
+ for (const line of over.lengths) say.warn(line)
1147
1378
  if (fileNote) say.warn(fileNote)
1148
1379
  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)}\`.`)
1149
1380
  // The pages it lands on, checked in the site's files where this project holds them.
@@ -1153,7 +1384,7 @@ async function writeDraft(args, kind) {
1153
1384
  console.log()
1154
1385
  await landingNotes(dir, landing.routes, { networks: landing.networks, goal: landing.goal })
1155
1386
  }
1156
- if (kind === 'post' && wentOut(deliveryOf(after, item)) === false) {
1387
+ if (kind === 'post' && wentOut(deliveryOf(after, item)) === false && !over.parts) {
1157
1388
  const sendAt = item?.data?.send_at
1158
1389
  if (deliveryOf(after, item)?.status === 'scheduled') say.dim(`Scheduled for ${sendAt}: \`uniweb promote unschedule ${id}\` makes it a draft again`)
1159
1390
  else say.dim(sendAt ? `Send it at its time, ${sendAt}: uniweb promote send ${id}` : `Send it: uniweb promote send ${id} [--at <time>]`)
@@ -1376,23 +1607,14 @@ async function send(args) {
1376
1607
  const scheduledFor = before?.status === 'scheduled' ? (post.data?.send_at ?? null) : null
1377
1608
 
1378
1609
  if (file) {
1379
- // `--at` moves the file's own send_at, so the one write carries it and the file keeps saying it.
1380
- let text = file.text
1381
- if (atGiven && !sameInstant(held, time)) {
1382
- text = fileWithFields(file.text, file.format, { send_at: time })
1383
- if (!text) {
1384
- say.err(`Could not set the time in ${arg}: give it \`send_at: ${time}\`, then send it.`)
1385
- return { exitCode: 2 }
1386
- }
1387
- }
1388
- const draft = text === file.text ? parsed.draft : parseDraft(text, { format: file.format, kind: 'post' }).draft
1610
+ // The file's draft is written first, as `post` writes it; a new time goes with the schedule, below.
1389
1611
  const wrote = await writeParsed({
1390
1612
  client,
1391
1613
  site,
1392
1614
  index,
1393
- input: { file: file.path, shown: arg, text, dir: dirname(file.path) },
1615
+ input: { file: file.path, shown: arg, text: file.text, dir: dirname(file.path) },
1394
1616
  format: file.format,
1395
- draft,
1617
+ draft: parsed.draft,
1396
1618
  kind: 'post'
1397
1619
  })
1398
1620
  if (!wrote.after) return wrote
@@ -1402,44 +1624,49 @@ async function send(args) {
1402
1624
  post = index.byUuid.get(wrote.plan.uuid)
1403
1625
  id = shortIds(index.items.map((i) => i.uuid)).get(post.uuid)
1404
1626
  before = deliveryOf(index, post)
1405
- if (writes && text === file.text && !json) say.info(`Wrote what ${arg} says to post ${id} first: it differed from the post as stored.`)
1627
+ if (writes && !json) say.info(`Wrote what ${arg} says to post ${id} first: it differed from the post as stored.`)
1628
+ }
1629
+
1630
+ // What its network takes: more parts is refused before anything goes out, a long part noted.
1631
+ const over = await limitsOf(client, index, post)
1632
+ if (over.parts) {
1633
+ say.err(`${over.parts} Nothing went out.`)
1634
+ return { exitCode: 2 }
1406
1635
  }
1636
+ if (!json) for (const line of over.lengths) say.warn(line)
1407
1637
 
1638
+ // A new time goes with the schedule itself, in one act refused whole, so a refusal leaves the
1639
+ // post as it was: still scheduled at its old time, or a draft.
1640
+ const moving = Boolean(when) && !sameInstant(post.data?.send_at, when)
1408
1641
  let res
1409
- let moved = false
1410
1642
  if (when) {
1411
- if (before?.status === 'scheduled' && sameInstant(post.data?.send_at, when)) {
1643
+ if (before?.status === 'scheduled' && !moving) {
1412
1644
  if (!json) say.ok(`Post ${id} is scheduled for ${post.data.send_at} already.`)
1413
1645
  return out(before, 0)
1414
1646
  }
1415
- if (!sameInstant(post.data?.send_at, when)) {
1416
- // The time is the post's own field, written first. A write makes a scheduled post a draft again.
1417
- const wrote = await client.writePromotionItems(site, [
1418
- { kind: 'update', uuid: post.uuid, data: { ...post.data, send_at: when }, if_unmodified_since: post.updated_at }
1419
- ])
1420
- if (!wrote.ok) {
1421
- await sayRefusal(wrote, { site, origin: client.origin, what: 'set its time', index })
1422
- return { exitCode: 1 }
1423
- }
1424
- post.data = { ...post.data, send_at: when }
1425
- moved = true
1426
- writes++
1427
- }
1428
- res = await client.postAction(site, post.uuid, 'schedule')
1647
+ res = await client.postAction(site, post.uuid, 'schedule', moving ? { send_at: when } : null)
1429
1648
  } else {
1430
1649
  res = await client.postAction(site, post.uuid, 'publish')
1431
1650
  }
1432
1651
  if (!res.ok) {
1433
1652
  await sayRefusal(res, { site, origin: client.origin, what: 'send posts', index })
1434
- // What this command wrote stays written, so say what the post is now.
1435
- if (scheduledFor && writes) {
1436
- 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.`)
1437
- } else if (moved) {
1438
- say.warn(`Post ${id}'s time is ${when} now, and it is not scheduled.`)
1439
- }
1653
+ // The file's changes stay written, and a write makes a scheduled post a draft again.
1654
+ if (scheduledFor && writes) say.warn(`Post ${id} was scheduled for ${scheduledFor}, and writing what ${arg} says made it a draft again: it is not scheduled now.`)
1440
1655
  return { exitCode: 1 }
1441
1656
  }
1442
1657
  const delivery = (await res.json().catch(() => null))?.delivery ?? null
1658
+ if (moving) {
1659
+ post.data = { ...post.data, send_at: when }
1660
+ // The file says the post's new time, at the version the schedule left, so its next run is not stale.
1661
+ if (file) {
1662
+ const after = await readIndex(client, site).catch(() => null)
1663
+ const item = after?.byUuid.get(post.uuid)
1664
+ const text = readFileSync(file.path, 'utf8')
1665
+ const next = item ? fileWithFields(text, file.format, { send_at: when, version: versionOf(after, item) }) : null
1666
+ if (next && next !== text) writeFileSync(file.path, next)
1667
+ else if (!next && !json) say.warn(`Could not write its new time into ${arg}: run \`uniweb promote show ${id} > ${arg}\` before you edit it again.`)
1668
+ }
1669
+ }
1443
1670
  if (json) return out(delivery, delivery?.status === 'failed' || delivery?.status === 'refused' ? 1 : 0)
1444
1671
  return { exitCode: sayDelivery(index, post, delivery, id) }
1445
1672
  }
@@ -1672,6 +1899,7 @@ export async function promote(args = []) {
1672
1899
  if (sub === 'status') return await status(args)
1673
1900
  if (sub === 'check') return await check(args)
1674
1901
  if (sub === 'connect') return await connectNetwork(args)
1902
+ if (sub === 'use') return await useAccount(args)
1675
1903
  if (sub === 'post' || sub === 'campaign') return await writeDraft(args, sub)
1676
1904
  if (sub === 'show') return await show(args)
1677
1905
  if (sub === 'delete') return await deleteItem(args)
@@ -1679,6 +1907,7 @@ export async function promote(args = []) {
1679
1907
  if (sub === 'unschedule') return await unschedule(args)
1680
1908
  if (sub === 'start' || sub === 'resume') return await spend(args, sub)
1681
1909
  if (sub === 'pause') return await pause(args)
1910
+ if (sub === 'results') return await results(args)
1682
1911
  } catch (err) {
1683
1912
  say.err(err instanceof WorkspaceMismatchError ? err.message : err?.message || String(err))
1684
1913
  return { exitCode: 1 }
@@ -108,7 +108,7 @@ import { resolveWorkspace, scopeOfWorkspace, topOfChildHandle, SOURCE_LABEL } fr
108
108
  import { writeJsonPreservingStyleAsync } from '../utils/json-file.js'
109
109
  import { newerInput } from '../utils/foundation-freshness.js'
110
110
  import { unregisteredLocalTypes } from '../backend/unregistered-types.js'
111
- import { typesFromLibraries } from '../backend/library-types.js'
111
+ import { typesFromLibraries, typesNamedBy } from '../backend/library-types.js'
112
112
  import {
113
113
  findWorkspaceRoot,
114
114
  findFoundations,
@@ -352,16 +352,6 @@ async function uploadVendorFiles(entities, files, { client }) {
352
352
  return true
353
353
  }
354
354
 
355
- /** A mapping's reverse `follow` lines' `model`s, as written. */
356
- function followModelsOf(decl) {
357
- const out = []
358
- for (const line of Array.isArray(decl?.follow) ? decl.follow : []) {
359
- if (!line || typeof line !== 'object') continue
360
- for (const spec of Object.values(line)) if (spec && typeof spec.model === 'string') out.push(spec.model)
361
- }
362
- return out
363
- }
364
-
365
355
  /**
366
356
  * Register the data schemas a library defines, before the foundation that names them
367
357
  * (`backend/library-types.js`): the library's package whole, as `uniweb register` there sends it.
@@ -394,7 +384,7 @@ async function registerLibraryTypes(lib, { client, exporter, at, upload = true }
394
384
  // of this library they name: a registry takes a mapping only after what it names.
395
385
  const mappings = await libraryMappingsWanted(lib, own)
396
386
  for (const decl of Object.values(mappings)) {
397
- for (const ref of [decl.model, ...followModelsOf(decl)]) {
387
+ for (const ref of typesNamedBy(decl)) {
398
388
  const local = typeof ref === 'string' ? own(ref) : null
399
389
  if (local && all[local]) wanted.add(local)
400
390
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-11-16T23:13:17.578Z",
3
+ "generatedAt": "2026-11-17T15:27:33.535Z",
4
4
  "packages": {
5
5
  "@uniweb/api": {
6
- "version": "1.7.2"
6
+ "version": "1.7.4"
7
7
  },
8
8
  "@uniweb/build": {
9
- "version": "1.24.1"
9
+ "version": "1.24.3"
10
10
  },
11
11
  "@uniweb/content-reader": {
12
12
  "version": "1.5.11"
@@ -114,9 +114,11 @@ const VERBS = {
114
114
  /**
115
115
  * `promote <command>` — a site's Promote. `--json` is every command's porcelain; `--site` names
116
116
  * a site this project isn't synced to; `--at` and `--now` are `send`'s time; `--yes` is what
117
- * `start` and `resume` take in place of their question; the workspace is `--org` / `--personal`.
117
+ * `start` and `resume` take in place of their question; `--connection` and `--target` are what
118
+ * `use` chooses; `--from` and `--to` are the days `results` reads; the workspace is `--org` /
119
+ * `--personal`.
118
120
  */
119
- promote: ['--json', '--site', '--at', '--now', '--yes', '--org', '--personal'],
121
+ promote: ['--json', '--site', '--at', '--now', '--yes', '--connection', '--target', '--from', '--to', '--org', '--personal'],
120
122
  status: [
121
123
  '--json', '--offline', '--dry-run',
122
124
  '--force', '--no-verify', '--no-validate', '--yes', '--org', '--personal',