rvlib-shipkit 2.19.0 → 2.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/package.json +1 -1
  3. package/src/annex/annex.ts +227 -0
  4. package/src/annex/offload.ts +279 -0
  5. package/src/checks/SK040-release-words.check.ts +43 -0
  6. package/src/checks/SK041-annex-links.check.ts +28 -0
  7. package/src/checks/SK042-post-kinds.check.ts +73 -0
  8. package/src/cli/cmd_Annex.ts +179 -0
  9. package/src/cli/cmd_Commands.ts +4 -1
  10. package/src/cli/cmd_Home.ts +3 -2
  11. package/src/cli/cmd_Messages.ts +155 -0
  12. package/src/cli/cmd_Releases.ts +48 -0
  13. package/src/cli/cmd_Review.ts +161 -6
  14. package/src/cli/cmd_Shot.ts +4 -4
  15. package/src/cli/cmd_Social.ts +143 -6
  16. package/src/cli/family-pages.ts +2 -0
  17. package/src/cli/kit/index.ts +1 -1
  18. package/src/cli/kit/verb.ts +11 -3
  19. package/src/cli/registry.ts +6 -1
  20. package/src/collections/collection-types.ts +8 -1
  21. package/src/collections/providers.ts +4 -1
  22. package/src/commands/model.ts +36 -0
  23. package/src/commands/registry.ts +49 -0
  24. package/src/commands/routes.ts +59 -0
  25. package/src/commands/runner.ts +35 -0
  26. package/src/commands/runs.ts +112 -0
  27. package/src/core/app-icon.ts +4 -3
  28. package/src/core/icon-type.ts +8 -0
  29. package/src/core/jobs.ts +4 -3
  30. package/src/core/layout.ts +5 -2
  31. package/src/core/squircle.ts +95 -0
  32. package/src/home/daemon-jobs.ts +26 -2
  33. package/src/home/global-units.ts +3 -0
  34. package/src/home/gui-app/ShipkitGui.swift +302 -5
  35. package/src/home/gui-app.ts +63 -33
  36. package/src/home/hmr-keep.ts +134 -0
  37. package/src/home/home-start.ts +2 -2
  38. package/src/home/lib-watch.ts +21 -11
  39. package/src/home/pm.ts +1 -1
  40. package/src/home/process-apps.ts +181 -0
  41. package/src/home/resources.ts +3 -3
  42. package/src/home/run-web.ts +7 -4
  43. package/src/home/serve-web.ts +64 -14
  44. package/src/identities/collection.ts +49 -0
  45. package/src/identities/identities.ts +110 -8
  46. package/src/identities/machine.ts +4 -3
  47. package/src/identities/rating.ts +33 -0
  48. package/src/identities/shown.ts +170 -0
  49. package/src/identities/steps.ts +5 -0
  50. package/src/media-store/purge.ts +15 -1
  51. package/src/media-store/remote.ts +22 -6
  52. package/src/messages/brief.ts +117 -0
  53. package/src/messages/collection.ts +40 -0
  54. package/src/messages/model.ts +171 -0
  55. package/src/messages/routes.ts +15 -0
  56. package/src/messages/score.ts +180 -0
  57. package/src/messages/tabs.ts +13 -0
  58. package/src/release/notes.ts +130 -0
  59. package/src/release/run-bump.ts +41 -18
  60. package/src/release/run-release.ts +22 -4
  61. package/src/release/run-releases.ts +17 -15
  62. package/src/release/unit-resolve.ts +9 -0
  63. package/src/releases/add.ts +66 -0
  64. package/src/releases/collection.ts +36 -0
  65. package/src/releases/from-card.ts +66 -0
  66. package/src/releases/model.ts +267 -0
  67. package/src/releases/pictures.ts +89 -0
  68. package/src/releases/routes.ts +36 -0
  69. package/src/releases/store.ts +71 -0
  70. package/src/repo-config.ts +5 -0
  71. package/src/review/cells.ts +0 -11
  72. package/src/review/format.ts +10 -6
  73. package/src/review/model.ts +92 -3
  74. package/src/review/notes.ts +2 -48
  75. package/src/review/routes.ts +28 -10
  76. package/src/review/stage-card.ts +197 -0
  77. package/src/review/stage-routes.ts +123 -0
  78. package/src/review/store.ts +36 -0
  79. package/src/review/trailer-card.ts +99 -0
  80. package/src/review/trailer-desk.ts +57 -4
  81. package/src/review/trailer-model.ts +41 -7
  82. package/src/review/trailer-notes.ts +45 -0
  83. package/src/review/trailer-routes.ts +22 -13
  84. package/src/serve/hub-app/app-bridge.ts +71 -0
  85. package/src/serve/hub-app/commands/commands-page.tsx +122 -0
  86. package/src/serve/hub-app/commands/commands-st.ts +177 -0
  87. package/src/serve/hub-app/commands.css +24 -0
  88. package/src/serve/hub-app/hash-route.ts +40 -1
  89. package/src/serve/hub-app/home-st.ts +11 -2
  90. package/src/serve/hub-app/home.html +3 -0
  91. package/src/serve/hub-app/hub-app.tsx +6 -0
  92. package/src/serve/hub-app/icons.tsx +5 -0
  93. package/src/serve/hub-app/identities-view.tsx +4 -1
  94. package/src/serve/hub-app/identities.css +1 -0
  95. package/src/serve/hub-app/index.html +3 -0
  96. package/src/serve/hub-app/keys.ts +2 -2
  97. package/src/serve/hub-app/machine-st.ts +41 -10
  98. package/src/serve/hub-app/messages/messages-page.tsx +354 -0
  99. package/src/serve/hub-app/messages/messages-st.ts +74 -0
  100. package/src/serve/hub-app/messages.css +35 -0
  101. package/src/serve/hub-app/releases/releases-page.tsx +94 -0
  102. package/src/serve/hub-app/releases/releases-st.ts +69 -0
  103. package/src/serve/hub-app/releases.css +25 -0
  104. package/src/serve/hub-app/repo-sections.ts +15 -1
  105. package/src/serve/hub-app/repo-st.ts +56 -5
  106. package/src/serve/hub-app/review/clip-st.ts +31 -3
  107. package/src/serve/hub-app/review/note-place.ts +31 -0
  108. package/src/serve/hub-app/review/review-cells.tsx +27 -3
  109. package/src/serve/hub-app/review/review-st.ts +77 -2
  110. package/src/serve/hub-app/review/review-thread.tsx +9 -31
  111. package/src/serve/hub-app/review/review-views.tsx +164 -58
  112. package/src/serve/hub-app/review/thread-st.ts +108 -41
  113. package/src/serve/hub-app/review/trailer-card.tsx +187 -0
  114. package/src/serve/hub-app/review/trailer-page.tsx +62 -31
  115. package/src/serve/hub-app/review/trailer-st.ts +138 -26
  116. package/src/serve/hub-app/review/trailer-timeline.tsx +39 -26
  117. package/src/serve/hub-app/review.css +49 -6
  118. package/src/serve/hub-app/social/comms-page.tsx +55 -23
  119. package/src/serve/hub-app/social/identity-pictures.ts +46 -8
  120. package/src/serve/hub-app/social/kit.tsx +9 -6
  121. package/src/serve/hub-app/social/post-card.tsx +10 -2
  122. package/src/serve/hub-app/social/social-model.ts +37 -3
  123. package/src/serve/hub-app/social/social-page.tsx +179 -65
  124. package/src/serve/hub-app/social/social-st.ts +79 -26
  125. package/src/serve/hub-app/social/stage-popup.tsx +268 -0
  126. package/src/serve/hub-app/social/stage-st.ts +310 -0
  127. package/src/serve/hub-app/social/step-layout.ts +42 -0
  128. package/src/serve/hub-app/social.css +60 -1
  129. package/src/serve/hub-app/tree-build.ts +38 -1
  130. package/src/serve/hub-app/tree-svc.ts +10 -3
  131. package/src/serve/project-gutter-route.ts +4 -2
  132. package/src/serve/same-origin.ts +24 -1
  133. package/src/serve/serve-hub.ts +15 -1
  134. package/src/shipkit-files.ts +9 -7
  135. package/src/shot/shooter.ts +3 -3
  136. package/src/shot/shot-ask.ts +14 -3
  137. package/src/shot/shot.shipkit.ts +1 -1
  138. package/src/social/discord-layout.ts +48 -5
  139. package/src/social/fit.ts +84 -0
  140. package/src/social/identity-words.ts +74 -0
  141. package/src/social/kind-pages.ts +41 -0
  142. package/src/social/kinds.ts +92 -0
  143. package/src/social/load.ts +105 -9
  144. package/src/social/media-limit.ts +63 -2
  145. package/src/social/presence.ts +1 -1
  146. package/src/social/publish/bluesky.ts +58 -19
  147. package/src/social/publish/index.ts +31 -5
  148. package/src/social/reach.ts +49 -0
  149. package/src/social/release-stage.ts +173 -0
  150. package/src/social/routes.ts +42 -7
  151. package/src/social/stage.ts +227 -0
  152. package/src/social/strip.ts +85 -0
  153. package/src/social/text.ts +6 -2
  154. package/src/social/unit.ts +57 -1
  155. package/src/social/writes.ts +11 -0
  156. package/src/trailer/build.ts +15 -2
  157. package/src/trailer/grammar.ts +14 -4
  158. package/src/trailer/public-words.ts +41 -0
@@ -1,4 +1,5 @@
1
- // the accounts shipkit posts to itself (`automation: live`): one publisher a platform, the desk's « Publish »
1
+ // the accounts shipkit posts to itself (`automation: live`): one publisher a platform, the desk's « Publish », and
2
+ // `sk social post --publish`, every waiting message of a draft on its live accounts (`--only` one of them)
2
3
  import { accountOf, draftPost, type Desk } from '../load.ts'
3
4
  import { setPosted } from '../writes.ts'
4
5
  import { postBluesky } from './bluesky.ts'
@@ -6,19 +7,44 @@ import { postDiscord } from './discord.ts'
6
7
  import type { Account } from '../../identities/identities.ts'
7
8
  import type { SocialPost } from '../load.ts'
8
9
 
9
- const PUBLISHERS: Readonly<Record<string, (a: Account, post: SocialPost) => Promise<string>>> = {
10
+ export type Publishers = Readonly<Record<string, (a: Account, post: SocialPost) => Promise<string>>>
11
+
12
+ const PUBLISHERS: Publishers = {
10
13
  discord: postDiscord,
11
14
  bluesky: postBluesky,
12
15
  }
13
16
 
14
- /** posts one message of a draft and records its link; the files written */
15
- export async function publish(desk: Desk, slug: string, key: string): Promise<{ url: string; files: string[] }> {
17
+ /** posts one message of a draft and records its link; the files written. `publishers` is a test's stub */
18
+ export async function publish(desk: Desk, slug: string, key: string, publishers: Publishers = PUBLISHERS): Promise<{ url: string; files: string[] }> {
16
19
  const post = draftPost(desk, slug, key)
17
20
  const a = accountOf(desk, post.identity, post.platform)
18
- const run = PUBLISHERS[post.platform]
21
+ if (post.refused !== '') throw new Error(`${slug} may not go out on ${a.name}: ${post.refused}`)
22
+ const run = publishers[post.platform]
19
23
  if (run == null) throw new Error(`${post.platform}: nothing posts there by itself`)
20
24
  if (a.automation !== 'live') throw new Error(`${a.file}: its automation is not live`)
21
25
  if (post.posted !== '' && post.platform !== 'discord') throw new Error(`${slug} is already posted on ${a.name}: ${post.posted}`)
22
26
  const url = await run(a, post)
23
27
  return { url, files: url === post.posted ? [] : setPosted(desk, slug, key, url) }
24
28
  }
29
+
30
+ /** each waiting message of a draft on a live account posted, the others named as waiting for his paste; `only` keeps
31
+ * one account's. `before` brings a media the disk let go back first */
32
+ export async function publishDraft(
33
+ desk: Desk,
34
+ slug: string,
35
+ o: { only?: string; publishers?: Publishers; before?: (p: SocialPost) => Promise<void> } = {},
36
+ ): Promise<{ key: string; line: string }[]> {
37
+ const d = desk.drafts.find((x) => x.slug === slug)
38
+ if (d == null) throw new Error(`no draft ${slug}`)
39
+ const out: { key: string; line: string }[] = []
40
+ for (const p of d.posts.filter((x) => o.only == null || x.platform === o.only)) {
41
+ const live = accountOf(desk, p.identity, p.platform).automation === 'live'
42
+ if (p.posted !== '') out.push({ key: p.key, line: `already posted, ${p.posted}` })
43
+ else if (!live) out.push({ key: p.key, line: 'waits for his paste' })
44
+ else {
45
+ await o.before?.(p)
46
+ out.push({ key: p.key, line: `posted, ${(await publish(desk, slug, p.key, o.publishers)).url}` })
47
+ }
48
+ }
49
+ return out
50
+ }
@@ -0,0 +1,49 @@
1
+ // where a rated message lands on an account (wiki tools/shipkit/social-identities.md, The accounts): every place has a
2
+ // ceiling, the most a post there may show; a Discord server's channels take theirs from its layout (age restricted:
3
+ // explicit, else safe), any other place from its `posts:`, the account's own profile (`me`) from the account's. A
4
+ // group's message goes to the account's place when it takes the rating, else to its first place in order that does,
5
+ // else it skips that account. Unrated is safe: fail closed
6
+ import { existsSync, readFileSync } from 'node:fs'
7
+ import { join } from 'node:path'
8
+ import { ME, type Account } from '../identities/identities.ts'
9
+ import { takes, type PostRating } from '../identities/rating.ts'
10
+ import { parseLayout } from './discord-layout.ts'
11
+
12
+ /** one place a message may land on, the most a post there may show, and whether everyone sees it: a group's message
13
+ * falls back only to a place everyone sees, never to a channel of a few roles */
14
+ export type Landing = { id: string; ceiling: PostRating; open: boolean }
15
+
16
+ /** an account's places in their order: its server's text channels when it has a layout, else its places/ files; a
17
+ * layout that does not read is an error line and lends no channel */
18
+ export function placesOf(a: Pick<Account, 'dir' | 'places'>, errors: string[]): Landing[] {
19
+ const layout = join(a.dir, 'layout.md')
20
+ if (!existsSync(layout)) return a.places.map((p) => ({ id: p.id, ceiling: p.ceiling, open: true }))
21
+ try {
22
+ const l = parseLayout(readFileSync(layout, 'utf8'), layout)
23
+ return l.categories.flatMap((c) =>
24
+ c.channels.filter((x) => !x.voice).map((x) => ({ id: x.name, ceiling: x.ageRestricted ? ('explicit' as const) : ('safe' as const), open: x.only.length === 0 })),
25
+ )
26
+ } catch (e) {
27
+ errors.push((e as Error).message)
28
+ return []
29
+ }
30
+ }
31
+
32
+ /** the account's places are its server's channels, read from a layout */
33
+ export const hasLayout = (a: Pick<Account, 'dir'>): boolean => existsSync(join(a.dir, 'layout.md'))
34
+
35
+ /** the ceiling of one place of the account, `me` or '' its own profile; null when the account has no such place */
36
+ export function ceilingAt(a: Pick<Account, 'ceiling'>, places: readonly Landing[], place: string): PostRating | null {
37
+ if (place === '' || place === ME) return a.ceiling
38
+ return places.find((p) => p.id === place)?.ceiling ?? null
39
+ }
40
+
41
+ /** where a group's message rated `r` lands on the account: its own place when that takes it, else its first place in
42
+ * order that does; a skip names why */
43
+ export function landing(a: Pick<Account, 'name' | 'place' | 'ceiling'>, places: readonly Landing[], r: PostRating): { place: string } | { skip: string } {
44
+ const own = ceilingAt(a, places, a.place)
45
+ if (own != null && takes(own, r)) return { place: a.place }
46
+ const other = places.find((p) => p.open && p.id !== a.place && takes(p.ceiling, r))
47
+ if (other != null) return { place: other.id }
48
+ return { skip: `${r} > ${own ?? 'safe'}: no place of ${a.name} takes ${/^[aeiou]/.test(r) ? 'an' : 'a'} ${r} post` }
49
+ }
@@ -0,0 +1,173 @@
1
+ // a release as the second source of a staged post (wiki tools/shipkit/social.md, A post staged): one draft for the
2
+ // beat, a heading per venue the repo's social unit declares, the release's message under each, its notes in its angle,
3
+ // its polish note raised. Its media is his pick, later, among the approved cards the release ships (a commit of theirs
4
+ // in its range). Idempotent: one draft a release. A repo with no `release` headings stages nothing
5
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
6
+ import { basename, dirname, join } from 'node:path'
7
+ import { isPostRating, type PostRating } from '../identities/rating.ts'
8
+ import { isApproved, verdictOf, type ReviewItem } from '../review/model.ts'
9
+ import { stageablesOf, stageFileOf, type Stageable } from '../review/stage-card.ts'
10
+ import { readAll, storeDir } from '../review/store.ts'
11
+ import { threadsOf, type Thread } from '../review/threads.ts'
12
+ import { changesOf, type Release } from '../releases/model.ts'
13
+ import { hasReleases, readRelease } from '../releases/store.ts'
14
+ import { gitBin } from '../core/git-bin.ts'
15
+ import { setHeadingText } from './drafts.ts'
16
+ import { DRAFT_NAME, draftsDir } from './load.ts'
17
+ import { parseFrontmatter, setMeta } from './md.ts'
18
+ import { askPolish, dryLoad, mediaFile, stageDraft, type Staged } from './stage.ts'
19
+ import { stripCopy } from './strip.ts'
20
+ import { guardWith, type SocialUnit } from './unit.ts'
21
+ import { commitPaths } from './writes.ts'
22
+
23
+ export type ReleaseAsk = {
24
+ /** the unit released, its id */
25
+ unit: string
26
+ version: string
27
+ /** the release's notes, markdown: its lines go to the angle and, with no message, under each heading */
28
+ notes: string
29
+ /** the short message for users, under each heading */
30
+ message?: string
31
+ /** the release's tag, and the one before it: the range whose approved cards lend it their media */
32
+ tag?: string
33
+ since?: string
34
+ /** the draft's title; unset, `<unit> <version>` */
35
+ title?: string
36
+ now?: Date
37
+ }
38
+
39
+ const head = (raw: string): Record<string, string> => parseFrontmatter(raw).meta
40
+
41
+ /** the draft a release already staged, by its `release:` */
42
+ export function releaseDraft(root: string, ref: string): string | null {
43
+ const dir = draftsDir(root)
44
+ if (!existsSync(dir)) return null
45
+ for (const slug of readdirSync(dir).sort()) {
46
+ if (!DRAFT_NAME.test(slug)) continue
47
+ const f = join(dir, slug, 'draft.md')
48
+ if (existsSync(f) && head(readFileSync(f, 'utf8')).release === ref) return slug
49
+ }
50
+ return null
51
+ }
52
+
53
+ /** markdown notes as post lines: its bullets, its plain lines; its headings and comments left out */
54
+ export function noteLines(md: string): string[] {
55
+ return md
56
+ .replace(/<!--[\s\S]*?-->/g, '')
57
+ .split('\n')
58
+ .map((l) => l.trim())
59
+ .filter((l) => l !== '' && !l.startsWith('#'))
60
+ .map((l) => (/^[-*+]\s/.test(l) ? `- ${l.slice(2).trim()}` : l))
61
+ }
62
+
63
+ /** one draft of the release, waiting in Communications: null when the unit declares no release headings; the draft
64
+ * already staged for the same release when there is one, nothing written */
65
+ export async function stageRelease(root: string, unit: SocialUnit | null, ask: ReleaseAsk, o: { speaksAs?: string; identitiesDir?: string | null } = {}): Promise<(Staged & { created: boolean }) | null> {
66
+ const headings = unit?.release?.headings
67
+ if (headings == null || headings.length === 0) return null
68
+ const ref = `${ask.unit}@${ask.version}`
69
+ const had = releaseDraft(root, ref)
70
+ if (had != null) return { slug: had, files: [], draft: null, errors: [], created: false }
71
+ // the release's file, when the repo keeps one, is its words: the notes handed in are only its fallback
72
+ const file = releaseFileOf(root, ref)
73
+ const lines = file ? changesOf(file).map((c) => `- ${c.title}`) : noteLines(ask.notes)
74
+ const text = (ask.message?.trim() ? noteLines(ask.message).join('\n') : lines.join('\n')) || `${ask.unit} ${ask.version} is out.`
75
+ const title = ask.title ?? (file?.title ? `${file.version}: ${file.title}` : `${ask.unit} ${ask.version}`)
76
+ const r = await stageDraft(
77
+ root,
78
+ {
79
+ source: { release: ref },
80
+ title,
81
+ text,
82
+ rating: 'safe',
83
+ status: 'draft',
84
+ headings,
85
+ angle: [`Staged from the release ${ref}${ask.tag ? ` (${ask.since ? `${ask.since}..` : ''}${ask.tag})` : ''}. Its notes:`, '', ...lines].join('\n'),
86
+ ...(ask.now ? { now: ask.now } : {}),
87
+ },
88
+ { unit, ...(o.speaksAs !== undefined ? { speaksAs: o.speaksAs } : {}), ...(o.identitiesDir !== undefined ? { identitiesDir: o.identitiesDir } : {}) },
89
+ )
90
+ // the range its media comes from, read back by Communications
91
+ if (ask.tag) {
92
+ const f = join(draftsDir(root), r.slug, 'draft.md')
93
+ writeFileSync(f, setMeta(readFileSync(f, 'utf8'), 'range', `${ask.since ? `${ask.since}..` : ''}${ask.tag}`))
94
+ commitPaths([f], `social: ${r.slug} names the range of ${ref}`)
95
+ }
96
+ await askPolish(root, r.slug, title, unit, 'release')
97
+ return { ...r, created: true }
98
+ }
99
+
100
+ /** the commits of a range, full shas; the range `a..b`, or a tag alone (every commit up to it) */
101
+ function commitsOf(root: string, range: string): Set<string> {
102
+ const r = Bun.spawnSync([gitBin(), 'rev-list', range], { cwd: root, stdout: 'pipe', stderr: 'pipe' })
103
+ if (r.exitCode !== 0) throw new Error(`git rev-list ${range}: ${r.stderr.toString().trim()}`)
104
+ return new Set(r.stdout.toString().split('\n').filter((l) => l !== ''))
105
+ }
106
+
107
+ /** the cards a release file names for `<unit>@<version>`, or null when the repo keeps no such file (only the root unit
108
+ * has release files: wiki tools/shipkit/units.md) */
109
+ function releasedCards(root: string, ref: string | undefined): Set<string> | null {
110
+ const r = releaseFileOf(root, ref)
111
+ return r == null ? null : new Set(changesOf(r).flatMap((c) => (c.card ? [c.card] : [])))
112
+ }
113
+
114
+ /** the release file of `<unit>@<version>`: the root unit's, named `root` or as the repo's folder; null without one */
115
+ export function releaseFileOf(root: string, ref: string | undefined): Release | null {
116
+ const m = ref ? /^([^@]+)@(\d+\.\d+\.\d+)$/.exec(ref) : null
117
+ if (!m || (m[1] !== 'root' && m[1] !== basename(root)) || !hasReleases(root)) return null
118
+ return readRelease(root, m[2]!)
119
+ }
120
+
121
+ /** the approved cards a release ships, newest first: a card its release file names, else one whose commit is in its
122
+ * range; its head's media */
123
+ export function releaseCards(root: string, slug: string): { range: string; cards: { id: string; title: string; media: Stageable[] }[] } {
124
+ const f = join(draftsDir(root), slug, 'draft.md')
125
+ if (!DRAFT_NAME.test(slug) || !existsSync(f)) throw new Error(`no draft ${slug}`)
126
+ const meta = head(readFileSync(f, 'utf8'))
127
+ const range = meta.range ?? ''
128
+ // the release's own file names its cards, one per change: its words and its media are one source
129
+ const listed = releasedCards(root, meta.release)
130
+ if (range === '' && listed == null) return { range, cards: [] }
131
+ const shas = listed == null ? [...commitsOf(root, range)] : []
132
+ const inRange = (c: string | undefined): boolean => c != null && c.length >= 7 && shas.some((s) => s.startsWith(c))
133
+ const items: ReviewItem[] = existsSync(storeDir(root)) ? readAll(storeDir(root)).items : []
134
+ const ships = (t: Thread): boolean => (listed == null ? inRange(t.head.item.commit) : t.versions.some((v) => listed.has(v.item.id)))
135
+ const cards = threadsOf(items)
136
+ .filter(ships)
137
+ .map((t) => t.head)
138
+ .filter((x) => x.item.origin.by === 'agent' && isApproved(verdictOf(x)?.status ?? 'rejected'))
139
+ .sort((a, b) => b.item.created.localeCompare(a.item.created))
140
+ .map((x) => ({ id: x.item.id, title: x.item.title, media: stageablesOf(x.item, 1) }))
141
+ return { range, cards }
142
+ }
143
+
144
+ /** a release draft with his picked media: the file copied clean into its media/, its `media`, `alt` and `rating` set,
145
+ * `## short` given his text; a dry run loads that on a scratch copy and writes nothing */
146
+ export async function releaseMedia(
147
+ root: string,
148
+ slug: string,
149
+ ask: { card: string; pick: string; rating: PostRating; alt?: string; text?: string; dry?: boolean },
150
+ o: { unit?: SocialUnit | null; speaksAs?: string; font?: string } = {},
151
+ ): Promise<Staged> {
152
+ if (!isPostRating(ask.rating)) throw new Error('rating: safe, mild or explicit')
153
+ const f = join(draftsDir(root), slug, 'draft.md')
154
+ const { cards } = releaseCards(root, slug)
155
+ const card = cards.find((c) => c.id === ask.card)
156
+ const m = card?.media.find((x) => x.key === ask.pick)
157
+ if (card == null || m == null) throw new Error(`${ask.pick} is no media of a card this release ships`)
158
+ const file = await stageFileOf(storeDir(root), m, o.font)
159
+ const name = mediaFile({ file, name: `release-${m.label.split(' ')[0]!.replace('.', '').toLowerCase()}-${card.id.slice(16, 40)}`, vertical: m.kind === 'clip' && m.ratio < 0.6 })
160
+ let raw = readFileSync(f, 'utf8')
161
+ raw = setMeta(setMeta(raw, 'media', name), 'rating', ask.rating)
162
+ if (ask.alt !== undefined) raw = setMeta(raw, 'alt', ask.alt.replace(/\s*\n\s*/g, ' ').trim())
163
+ if (ask.text?.trim()) raw = setHeadingText(raw, 'short', ask.text)
164
+ const c = { ...(o.unit !== undefined ? { unit: o.unit } : {}), ...(o.speaksAs !== undefined ? { speaksAs: o.speaksAs } : {}) }
165
+ const problems = guardWith(o.unit, { alt: ask.alt ?? '', texts: ask.text ? [ask.text] : [], files: [file] })
166
+ if (problems.length > 0 && !ask.dry) throw new Error(`the repo's guard refuses it: ${problems.join('; ')}`)
167
+ if (ask.dry) return dryLoad(root, slug, raw, { name, file }, c)
168
+ mkdirSync(dirname(join(draftsDir(root), slug, name)), { recursive: true })
169
+ stripCopy(file, join(draftsDir(root), slug, name))
170
+ writeFileSync(f, raw)
171
+ commitPaths([f, join(draftsDir(root), slug, name)], `social: ${slug} takes the media of the card ${card.id}`)
172
+ return { slug, files: [f], draft: null, errors: [] }
173
+ }
@@ -6,7 +6,10 @@ import { existsSync } from 'node:fs'
6
6
  import { homedir } from 'node:os'
7
7
  import { isAbsolute, join, relative, resolve } from 'node:path'
8
8
  import { bad, FRESH, NO_STORE, ranged } from '../review/http.ts'
9
- import { askedPosts, noteOn, notesBy } from '../review/notes.ts'
9
+ import { noteOn, notesBy } from '../review/notes.ts'
10
+ import { answerOf, voiceOf } from '../review/stage-routes.ts'
11
+ import { isPostRating } from '../identities/rating.ts'
12
+ import { noteLines, releaseCards, releaseMedia } from './release-stage.ts'
10
13
  import { readAllCached, storeDir } from '../review/store.ts'
11
14
  import { DRAFT_NAME, draftsDir, type Desk } from './load.ts'
12
15
  import { deskAnswer } from './desk-index.ts'
@@ -16,7 +19,8 @@ import { openAll } from '../veille/chrome.ts'
16
19
  import { noteOpen, searchHistory, settleSeen, trackerView } from './tracker.ts'
17
20
  import { publish } from './publish/index.ts'
18
21
  import { socialStats } from './stats.ts'
19
- import { setLive, setPosted, setStep, setText } from './writes.ts'
22
+ import { setLive, setPosted, setShown, setStep, setText } from './writes.ts'
23
+ import { pictureVersion } from '../identities/identities.ts'
20
24
 
21
25
  const KEY = /^[a-z0-9-]+(?:\/[a-z0-9-]+)?$/
22
26
  const ID = /^[a-z0-9-]+$/
@@ -39,6 +43,8 @@ function draftMedia(desk: Desk, slug: string, name: string): string {
39
43
  throw new Error(`${slug} names no media ${name}`)
40
44
  }
41
45
 
46
+ const IMMUTABLE = { 'Cache-Control': 'public, max-age=31536000, immutable' }
47
+
42
48
  /** a picture under an identity's `files` folder, or one its `pictures` list from a folder elsewhere; never another */
43
49
  function picture(desk: Desk, identity: string, rel: string): string {
44
50
  const i = desk.identities.find((x) => x.id === identity)
@@ -71,15 +77,23 @@ export async function socialRoutes(root: string, req: Request, path: string): Pr
71
77
  for (const i of desk.identities) out[i.id] = trackerView(i.id)
72
78
  return Response.json(out, { headers: NO_STORE })
73
79
  }
74
- if (sub === 'asked') {
75
- const dir = storeDir(root)
76
- return Response.json({ asked: askedPosts(readAllCached(dir).items) }, { headers: NO_STORE })
77
- }
78
80
  if (sub === 'notes') {
79
81
  const slug = str(new URL(req.url).searchParams.get('slug'), 'draft', DRAFT_NAME)
80
82
  const dir = storeDir(root)
81
83
  return Response.json({ notes: notesBy(dir, readAllCached(dir).items)({ kind: 'draft', slug }) }, { headers: NO_STORE })
82
84
  }
85
+ // a release draft's stage popup: the approved cards it ships as its media strip, its notes as chips
86
+ if (sub === 'release-media') {
87
+ const slug = str(new URL(req.url).searchParams.get('slug'), 'draft', DRAFT_NAME)
88
+ const { desk } = await openDesk(root)
89
+ const d = desk.drafts.find((x) => x.slug === slug)
90
+ if (d?.release == null) return bad(`${slug} is no release draft`, 404)
91
+ const { range, cards } = releaseCards(root, slug)
92
+ const words = noteLines(d.angle).filter((l) => !l.startsWith('Staged from')).map((l) => ({ from: 'card' as const, text: l.replace(/^- /, '') }))
93
+ const voice = await voiceOf(root, { id: slug, title: d.title })
94
+ const media = cards.flatMap((c) => c.media.map((m) => ({ ...m, label: `${m.label.replace(/^1\./, '')} · ${c.title}` })))
95
+ return Response.json({ head: slug, first: slug, title: d.title, media, words, ...voice, rating: d.rating, drafts: [], range }, { headers: NO_STORE })
96
+ }
83
97
  const media = /^media\/([^/]+)\/(.+)$/.exec(sub)
84
98
  if (media) {
85
99
  const { desk } = await openDesk(root)
@@ -91,7 +105,10 @@ export async function socialRoutes(root: string, req: Request, path: string): Pr
91
105
  const pic = /^picture\/([a-z0-9-]+)\/(.+)$/.exec(sub)
92
106
  if (pic) {
93
107
  const { desk } = await openDesk(root)
94
- return ranged(req, picture(desk, pic[1]!, decodeURIComponent(pic[2]!)), FRESH)
108
+ const abs = picture(desk, pic[1]!, decodeURIComponent(pic[2]!))
109
+ // a url naming the file's version as it is now keeps for good; an old version or none is asked again
110
+ const v = new URL(req.url).searchParams.get('v')
111
+ return ranged(req, abs, v != null && v !== '' && v === pictureVersion(abs) ? IMMUTABLE : FRESH)
95
112
  }
96
113
  const prev = /^preview\/([^/]+)$/.exec(sub)
97
114
  if (prev) {
@@ -117,6 +134,20 @@ export async function socialRoutes(root: string, req: Request, path: string): Pr
117
134
  const text = String(b.text ?? '')
118
135
  return Response.json(await noteOn(storeDir(root), { subject: { kind: 'draft', slug }, origin: { by: 'owner', from: 'communications' }, topic: unit?.notes ?? 'social', name: String(b.title ?? '') || slug, text }))
119
136
  }
137
+ if (sub === 'release-media') {
138
+ const { desk, unit } = await openDesk(root)
139
+ const slug = str(b.slug, 'draft', DRAFT_NAME)
140
+ const pick = str(b.pick, 'media')
141
+ const rating = str(b.rating, 'rating')
142
+ if (!isPostRating(rating)) throw new Error('rating: safe, mild or explicit')
143
+ const r = await releaseMedia(
144
+ root,
145
+ slug,
146
+ { card: pick.split('#')[0]!, pick, rating, ...(typeof b.alt === 'string' ? { alt: b.alt } : {}), ...(typeof b.text === 'string' ? { text: b.text } : {}), dry: b.dry === true },
147
+ { unit, ...(desk.speaksAs ? { speaksAs: desk.speaksAs } : {}) },
148
+ )
149
+ return Response.json(answerOf(r), { headers: NO_STORE })
150
+ }
120
151
  if (sub === 'reveal') {
121
152
  const { desk } = await openDesk(root)
122
153
  // an identity's picture, or a draft's media (brought back from the Space when the disk let it go)
@@ -129,6 +160,8 @@ export async function socialRoutes(root: string, req: Request, path: string): Pr
129
160
  const { desk } = await openDesk(root)
130
161
  if (sub === 'posted') return Response.json({ files: setPosted(desk, str(b.slug, 'draft', DRAFT_NAME), str(b.key, 'message', KEY), urlOrNull(b.url)) })
131
162
  if (sub === 'live') return Response.json({ files: setLive(desk, str(b.identity, 'identity', ID), str(b.account, 'account', ID), urlOrNull(b.url)) })
163
+ if (sub === 'shown')
164
+ return Response.json({ files: setShown(desk, str(b.identity, 'identity', ID), str(b.account, 'account', ID), str(b.row, 'row'), typeof b.file === 'string' ? b.file : undefined, typeof b.sha === 'string' ? b.sha : undefined) })
132
165
  if (sub === 'step') {
133
166
  const index = Number(b.index)
134
167
  if (!Number.isInteger(index) || index < 0) throw new Error(`step ${String(b.index)}?`)
@@ -165,6 +198,8 @@ export async function socialRoutes(root: string, req: Request, path: string): Pr
165
198
  const d = desk.drafts.find((x) => x.slug === slug)
166
199
  const posts = d?.posts.filter((p) => p.from === from) ?? []
167
200
  if (d == null || posts.length === 0) return bad(`no message ${from} in ${slug}`, 404)
201
+ const refused = posts.find((p) => p.refused !== '')
202
+ if (refused != null) return bad(`${slug} may not go out: ${refused.refused}`)
168
203
  const accounts = desk.identities.find((i) => i.id === d.identity)?.accounts ?? []
169
204
  // a live account posts with « Publish », a posted one is done: neither needs a window
170
205
  const open = posts.flatMap((p) => {
@@ -0,0 +1,227 @@
1
+ // a post staged from a source (wiki tools/shipkit/social.md, A post staged): a review card's media, or a release's
2
+ // notes, written as one v3 draft at once, the media copied in with its metadata left out, committed by its own paths.
3
+ // The repo's guard runs before anything is written, so a draft it refuses never sits on the disk. A dry run writes the
4
+ // same draft into a scratch folder and loads it, so the popup's counts, places and problems are the desk's own. Staging
5
+ // never posts: publishing stays his act in Communications
6
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
7
+ import { tmpdir } from 'node:os'
8
+ import { dirname, extname, join, relative } from 'node:path'
9
+ import { LAYOUT } from '../core/layout.ts'
10
+ import { identitiesDir, loadIdentities } from '../identities/identities.ts'
11
+ import type { PostRating } from '../identities/rating.ts'
12
+ import { loadRepoConfig } from '../repo-config.ts'
13
+ import { idOf } from '../review/model.ts'
14
+ import { DRAFT_NAME, draftsDir, loadDesk, VERTICAL, type Draft } from './load.ts'
15
+ import { fitTo, tightest } from './fit.ts'
16
+ import { kindProblem, sourceKind } from './kinds.ts'
17
+ import { stripCopy } from './strip.ts'
18
+ import { guardWith, loadSocialUnit, type ReleaseHeading, type SocialUnit } from './unit.ts'
19
+ import { commitPaths } from './writes.ts'
20
+
21
+ /** where a staged draft comes from: a review card (any id of its thread), or a release `<unit>@<version>` */
22
+ export type StageSource = { review: string } | { release: string }
23
+
24
+ export type StageMedia = {
25
+ /** the local file, absolute */
26
+ file: string
27
+ /** what its copy is called, without the extension: `<topic>-<view>` */
28
+ name: string
29
+ /** a 9:16 clip: the draft gets its `## vertical` too */
30
+ vertical?: boolean
31
+ }
32
+
33
+ export type StageInput = {
34
+ source: StageSource
35
+ title: string
36
+ /** his text, under each heading */
37
+ text: string
38
+ media?: StageMedia | null
39
+ alt?: string
40
+ rating: PostRating
41
+ /** unset, its source's: `feature` from a card, `release` from a release (wiki guides/post-kinds/index.md) */
42
+ kind?: string
43
+ /** a `custom` kind's one line on why no kind fits */
44
+ kindWhy?: string
45
+ /** `picked` unset: his own act chose it */
46
+ status?: 'draft' | 'picked'
47
+ /** `<YYYY-MM-DD> <tag>`, a slot of the rhythm */
48
+ slot?: string
49
+ /** `#a #b` */
50
+ tags?: string
51
+ angle: string
52
+ /** the headings the text goes under; unset, `short` */
53
+ headings?: readonly ReleaseHeading[]
54
+ now?: Date
55
+ }
56
+
57
+ export type Staged = { slug: string; files: string[]; draft: Draft | null; errors: string[] }
58
+
59
+ const sourceLine = (s: StageSource): string => ('review' in s ? `review: ${s.review}` : `release: ${s.release}`)
60
+
61
+ /** the kind a stage writes: the one asked, else its source's */
62
+ const kindOf = (input: Pick<StageInput, 'kind' | 'source'>): string => input.kind?.trim() || sourceKind(input.source)
63
+
64
+ /** the name a staged media's copy takes in its draft, `media/<name>[-vertical].<ext>` */
65
+ export const mediaFile = (m: StageMedia): string => {
66
+ const ext = extname(m.file).toLowerCase()
67
+ return `media/${m.name}${m.vertical && ext === '.mp4' ? '-vertical' : ''}${ext === '.jpeg' ? '.jpg' : ext}`
68
+ }
69
+
70
+ /** the draft.md a stage writes, `media` its media name as the draft gives it */
71
+ export function draftText(input: StageInput, media: string | null): string {
72
+ const one = (v: string | undefined): string => (v ?? '').replace(/\s*\n\s*/g, ' ').trim()
73
+ const head = [
74
+ `title: ${one(input.title)}`,
75
+ `kind: ${kindOf(input)}`,
76
+ ...(one(input.kindWhy) ? [`kindWhy: ${one(input.kindWhy)}`] : []),
77
+ `status: ${input.status ?? 'picked'}`,
78
+ `rating: ${input.rating}`,
79
+ ...(media ? [`media: ${media}`] : []),
80
+ ...(one(input.alt) ? [`alt: ${one(input.alt)}`] : []),
81
+ ...(input.slot ? [`slot: ${input.slot}`] : []),
82
+ sourceLine(input.source),
83
+ ]
84
+ const text = input.text.trim()
85
+ if (/^## /m.test(text)) throw new Error('the text holds a "## " line: it would start a heading')
86
+ const tags = one(input.tags)
87
+ const opts = (h: ReleaseHeading, tagged: boolean): string => {
88
+ const o = [...(h.place ? [`place: ${h.place}`] : []), ...(tagged && tags ? [`tags: ${tags}`] : [])]
89
+ return o.length ? ` (${o.join(', ')})` : ''
90
+ }
91
+ const headings = input.headings ?? [{ id: 'short' }]
92
+ const body = headings.map((h) => `## ${h.id}${opts(h, h.id === 'short')}\n\n${text}`)
93
+ if (media?.endsWith('-vertical.mp4') && !headings.some((h) => h.id === VERTICAL)) body.push(`## ${VERTICAL}${tags ? ` (tags: ${tags})` : ''}\n\n${text}`)
94
+ return `---\n${head.join('\n')}\n---\n\n## Angle\n\n${input.angle.trim()}\n\n${body.join('\n\n')}\n`
95
+ }
96
+
97
+ /** the slug a stage at `now` gives a title */
98
+ export const stageSlug = (title: string, now: Date): string => idOf(now, title)
99
+
100
+ /** the guard's problems with what the stage would write, and its kind's: run before any file is. A stage never writes
101
+ * an old word or a custom with no reason, so every kind problem refuses it */
102
+ export function guardStage(unit: SocialUnit | null, input: StageInput): string[] {
103
+ const kind = kindProblem(kindOf(input), input.kindWhy ?? '', unit?.kinds ?? [])
104
+ return [
105
+ ...guardWith(unit, { title: input.title, alt: input.alt ?? '', texts: [input.text, ...(input.tags?.trim() ? [input.tags] : [])], files: input.media ? [input.media.file] : [] }),
106
+ ...(kind ? [kind.text] : []),
107
+ ]
108
+ }
109
+
110
+ type Ctx = { unit: SocialUnit | null; speaksAs: string | undefined; identitiesDir?: string | null }
111
+
112
+ async function contextOf(root: string, o: Partial<Ctx>): Promise<Ctx> {
113
+ const speaksAs = 'speaksAs' in o ? o.speaksAs : (await loadRepoConfig(root, { fresh: true }).catch(() => null))?.speaksAs
114
+ const unit = 'unit' in o ? (o.unit ?? null) : await loadSocialUnit(root)
115
+ // the folder is the real repo's house, resolved here: a dry run loads from a scratch folder that has none
116
+ return { unit, speaksAs, identitiesDir: o.identitiesDir !== undefined ? o.identitiesDir : await identitiesDir(root) }
117
+ }
118
+
119
+ /** one draft as the desk loads it, and the load's lines about it */
120
+ async function loadOne(root: string, slug: string, c: Ctx): Promise<{ draft: Draft | null; errors: string[] }> {
121
+ const ids = await loadIdentities({ ...(c.identitiesDir !== undefined ? { dir: c.identitiesDir } : {}), cwd: root })
122
+ const desk = loadDesk(root, ids, { speaksAs: c.speaksAs, unit: c.unit })
123
+ return { draft: desk.drafts.find((d) => d.slug === slug) ?? null, errors: desk.errors.filter((e) => e.includes(slug)) }
124
+ }
125
+
126
+ /** the draft a stage would write, loaded from a scratch folder: its messages, the accounts it skips, every problem.
127
+ * Its media is named where it is, never copied */
128
+ export async function stageDry(root: string, input: StageInput, o: Partial<Ctx> = {}): Promise<Staged> {
129
+ const c = await contextOf(root, o)
130
+ const slug = stageSlug(input.title, input.now ?? new Date())
131
+ // a vertical's name, so the load reads it as one, on a link to the very file
132
+ const media = input.media ? mediaFile(input.media) : null
133
+ const r = await dryLoad(root, slug, draftText(input, media), input.media && media ? { name: media, file: input.media.file } : null, c)
134
+ return { ...r, errors: [...new Set([...guardStage(c.unit, input), ...r.errors])] }
135
+ }
136
+
137
+ /** one draft's text loaded from a scratch copy of the social folder (its rhythm, a link to its media): the desk's own
138
+ * lines about it, its path left out of each */
139
+ export async function dryLoad(root: string, slug: string, raw: string, media: { name: string; file: string } | null, o: Partial<Ctx> = {}): Promise<Staged> {
140
+ const c = await contextOf(root, o)
141
+ const scratch = mkdtempSync(join(tmpdir(), 'stage-dry-'))
142
+ try {
143
+ const dir = join(draftsDir(scratch), slug)
144
+ mkdirSync(dir, { recursive: true })
145
+ const rhythm = join(root, LAYOUT.social, 'rhythm.md')
146
+ if (existsSync(rhythm)) copyFileSync(rhythm, join(scratch, LAYOUT.social, 'rhythm.md'))
147
+ if (media) {
148
+ mkdirSync(dirname(join(dir, media.name)), { recursive: true })
149
+ symlinkSync(media.file, join(dir, media.name))
150
+ }
151
+ writeFileSync(join(dir, 'draft.md'), raw)
152
+ const { draft, errors } = await loadOne(scratch, slug, c)
153
+ return { slug, files: [], draft, errors: [...new Set(errors.map((e) => e.replace(`${relative(scratch, join(dir, 'draft.md'))}: `, '')))] }
154
+ } finally {
155
+ rmSync(scratch, { recursive: true, force: true })
156
+ }
157
+ }
158
+
159
+ /** « fit »: the media made one copy within the tightest limits of the venues the draft reaches (a dry stage says which);
160
+ * the input as it was when the media fits already */
161
+ export async function fitStage(root: string, input: StageInput, o: Partial<Ctx> = {}): Promise<StageInput> {
162
+ if (!input.media) return input
163
+ const c = await contextOf(root, o)
164
+ const dry = await stageDry(root, input, c)
165
+ const ids = await loadIdentities({ ...(c.identitiesDir !== undefined ? { dir: c.identitiesDir } : {}), cwd: root })
166
+ const reached = new Set((dry.draft?.posts ?? []).map((p) => p.platform))
167
+ const who = ids.identities.find((i) => i.id === dry.draft?.identity)
168
+ const limits = (who?.accounts ?? []).filter((a) => reached.has(a.id)).map((a) => a.limits)
169
+ const file = await fitTo(input.media.file, tightest(limits))
170
+ return file === input.media.file ? input : { ...input, media: { ...input.media, file } }
171
+ }
172
+
173
+ /** « ✍️ polish »: the draft note (wiki tools/shipkit/social-desks.md) asking an agent to rewrite each heading in the
174
+ * identity's voice and fill its alt, raised to the social unit's notes topic where the store has it */
175
+ export async function askPolish(root: string, slug: string, title: string, unit: SocialUnit | null, why = 'staged'): Promise<{ id: string }> {
176
+ const { noteOn } = await import('../review/notes.ts')
177
+ const { specOf, storeDir } = await import('../review/store.ts')
178
+ const dir = storeDir(root)
179
+ const spec = specOf(dir)
180
+ const want = unit?.notes ?? 'social'
181
+ const topic = Object.keys(spec.topics).length === 0 || spec.topics[want] ? want : undefined
182
+ return noteOn(dir, {
183
+ subject: { kind: 'draft', slug },
184
+ origin: { by: 'owner', from: why === 'staged' ? 'stage' : why },
185
+ name: title || slug,
186
+ text: `polish: rewrite each heading of ${slug} in the identity's voice, each venue its own words within its max, fill its alt, keep its media and rating`,
187
+ ...(topic ? { topic } : {}),
188
+ what: [
189
+ `Polish the ${why} draft « ${title} » (\`.shipkit/social/drafts/${slug}/draft.md\`).`,
190
+ "- each heading's text in the identity's voice (wiki preferences/writing-voice/index.md and the project's voice page), never the same botcopy twice",
191
+ '- the alt describes the media; the rating and the media stay',
192
+ '- the repo guard must pass: `sk social` shows no line for it',
193
+ '- then close this note: `sk review fixed <this id> --note "polished"`',
194
+ ].join('\n'),
195
+ })
196
+ }
197
+
198
+ /** the draft written in the repo, its media copied in clean, then committed by its own paths; refused before any
199
+ * write while the repo's guard names a problem. The load's lines about the written draft come back with it */
200
+ export async function stageDraft(root: string, input: StageInput, o: Partial<Ctx> = {}): Promise<Staged> {
201
+ const c = await contextOf(root, o)
202
+ const problems = guardStage(c.unit, input)
203
+ if (problems.length > 0) throw new Error(`the repo's guard refuses it: ${problems.join('; ')}`)
204
+ if (input.media && !existsSync(input.media.file)) throw new Error(`no media ${input.media.file}`)
205
+ const slug = stageSlug(input.title, input.now ?? new Date())
206
+ if (!DRAFT_NAME.test(slug)) throw new Error(`draft ${slug}?`)
207
+ const dir = join(draftsDir(root), slug)
208
+ if (existsSync(dir)) throw new Error(`drafts/${slug} already exists`)
209
+ const media = input.media ? mediaFile(input.media) : null
210
+ const files: string[] = []
211
+ mkdirSync(dir, { recursive: true })
212
+ try {
213
+ if (input.media && media) {
214
+ mkdirSync(join(dir, 'media'), { recursive: true })
215
+ stripCopy(input.media.file, join(dir, media))
216
+ files.push(join(dir, media))
217
+ }
218
+ writeFileSync(join(dir, 'draft.md'), draftText(input, media))
219
+ files.unshift(join(dir, 'draft.md'))
220
+ } catch (e) {
221
+ rmSync(dir, { recursive: true, force: true })
222
+ throw e
223
+ }
224
+ const { draft, errors } = await loadOne(root, slug, c)
225
+ commitPaths(files, `social: ${slug} staged from ${'review' in input.source ? `the card ${input.source.review}` : `the release ${input.source.release}`}`)
226
+ return { slug, files, draft, errors }
227
+ }