@prenta/admin 2.7.0 → 2.9.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 (211) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/design-system/tokens.css +17 -0
  3. package/design-system/tokens.json +35 -1
  4. package/design-system/tokens.scss +15 -0
  5. package/design-system/tokens.tailwind.cjs +14 -0
  6. package/dist/AdminRoot.d.ts.map +1 -1
  7. package/dist/AdminRoot.js +7 -7
  8. package/dist/AdminRoot.js.map +1 -1
  9. package/dist/__tests__/components/batch-ai-actions.test.js +4 -0
  10. package/dist/__tests__/components/batch-ai-actions.test.js.map +1 -1
  11. package/dist/__tests__/lib/batch-wizard.test.d.ts +2 -0
  12. package/dist/__tests__/lib/batch-wizard.test.d.ts.map +1 -0
  13. package/dist/__tests__/lib/batch-wizard.test.js +227 -0
  14. package/dist/__tests__/lib/batch-wizard.test.js.map +1 -0
  15. package/dist/__tests__/lib/job-drawer.test.js +2 -0
  16. package/dist/__tests__/lib/job-drawer.test.js.map +1 -1
  17. package/dist/__tests__/lib/job-view.test.js +100 -3
  18. package/dist/__tests__/lib/job-view.test.js.map +1 -1
  19. package/dist/__tests__/lib/jobs-service.test.js +74 -2
  20. package/dist/__tests__/lib/jobs-service.test.js.map +1 -1
  21. package/dist/__tests__/views/appearance-chrome.render.test.d.ts +2 -0
  22. package/dist/__tests__/views/appearance-chrome.render.test.d.ts.map +1 -0
  23. package/dist/__tests__/views/appearance-chrome.render.test.js +688 -0
  24. package/dist/__tests__/views/appearance-chrome.render.test.js.map +1 -0
  25. package/dist/__tests__/views/header-footer-form.test.d.ts +2 -0
  26. package/dist/__tests__/views/header-footer-form.test.d.ts.map +1 -0
  27. package/dist/__tests__/views/header-footer-form.test.js +266 -0
  28. package/dist/__tests__/views/header-footer-form.test.js.map +1 -0
  29. package/dist/__tests__/views/jobs-drawer.render.test.js +442 -2
  30. package/dist/__tests__/views/jobs-drawer.render.test.js.map +1 -1
  31. package/dist/__tests__/views/jobs-list.render.test.js +7 -5
  32. package/dist/__tests__/views/jobs-list.render.test.js.map +1 -1
  33. package/dist/__tests__/views/jobs-wizard.render.test.d.ts +2 -0
  34. package/dist/__tests__/views/jobs-wizard.render.test.d.ts.map +1 -0
  35. package/dist/__tests__/views/jobs-wizard.render.test.js +588 -0
  36. package/dist/__tests__/views/jobs-wizard.render.test.js.map +1 -0
  37. package/dist/__tests__/views/run-with-ai.render.test.d.ts +2 -0
  38. package/dist/__tests__/views/run-with-ai.render.test.d.ts.map +1 -0
  39. package/dist/__tests__/views/run-with-ai.render.test.js +689 -0
  40. package/dist/__tests__/views/run-with-ai.render.test.js.map +1 -0
  41. package/dist/components/BatchAiActions.d.ts +8 -1
  42. package/dist/components/BatchAiActions.d.ts.map +1 -1
  43. package/dist/components/BatchAiActions.js +3 -2
  44. package/dist/components/BatchAiActions.js.map +1 -1
  45. package/dist/lib/api.d.ts +2 -0
  46. package/dist/lib/api.d.ts.map +1 -1
  47. package/dist/lib/api.js +8 -1
  48. package/dist/lib/api.js.map +1 -1
  49. package/dist/lib/batch-wizard.d.ts +118 -0
  50. package/dist/lib/batch-wizard.d.ts.map +1 -0
  51. package/dist/lib/batch-wizard.js +216 -0
  52. package/dist/lib/batch-wizard.js.map +1 -0
  53. package/dist/lib/chrome-service.d.ts +69 -0
  54. package/dist/lib/chrome-service.d.ts.map +1 -0
  55. package/dist/lib/chrome-service.js +108 -0
  56. package/dist/lib/chrome-service.js.map +1 -0
  57. package/dist/lib/job-view.d.ts +43 -0
  58. package/dist/lib/job-view.d.ts.map +1 -1
  59. package/dist/lib/job-view.js +57 -1
  60. package/dist/lib/job-view.js.map +1 -1
  61. package/dist/lib/jobs-service.d.ts +48 -1
  62. package/dist/lib/jobs-service.d.ts.map +1 -1
  63. package/dist/lib/jobs-service.js +50 -0
  64. package/dist/lib/jobs-service.js.map +1 -1
  65. package/dist/prenta-admin.css +1 -1
  66. package/dist/views/AppearanceChrome.d.ts +22 -4
  67. package/dist/views/AppearanceChrome.d.ts.map +1 -1
  68. package/dist/views/AppearanceChrome.js +451 -15
  69. package/dist/views/AppearanceChrome.js.map +1 -1
  70. package/dist/views/CollectionList.d.ts +3 -1
  71. package/dist/views/CollectionList.d.ts.map +1 -1
  72. package/dist/views/CollectionList.js +5 -2
  73. package/dist/views/CollectionList.js.map +1 -1
  74. package/dist/views/Jobs/CancelJobDialog.d.ts +7 -1
  75. package/dist/views/Jobs/CancelJobDialog.d.ts.map +1 -1
  76. package/dist/views/Jobs/CancelJobDialog.js +13 -3
  77. package/dist/views/Jobs/CancelJobDialog.js.map +1 -1
  78. package/dist/views/Jobs/DrawerOverview.d.ts +6 -2
  79. package/dist/views/Jobs/DrawerOverview.d.ts.map +1 -1
  80. package/dist/views/Jobs/DrawerOverview.js +6 -3
  81. package/dist/views/Jobs/DrawerOverview.js.map +1 -1
  82. package/dist/views/Jobs/DrawerResults.d.ts +13 -3
  83. package/dist/views/Jobs/DrawerResults.d.ts.map +1 -1
  84. package/dist/views/Jobs/DrawerResults.js +37 -3
  85. package/dist/views/Jobs/DrawerResults.js.map +1 -1
  86. package/dist/views/Jobs/DrawerReview.d.ts +7 -0
  87. package/dist/views/Jobs/DrawerReview.d.ts.map +1 -1
  88. package/dist/views/Jobs/DrawerReview.js +1 -1
  89. package/dist/views/Jobs/DrawerReview.js.map +1 -1
  90. package/dist/views/Jobs/JobDrawer.d.ts +26 -3
  91. package/dist/views/Jobs/JobDrawer.d.ts.map +1 -1
  92. package/dist/views/Jobs/JobDrawer.js +30 -5
  93. package/dist/views/Jobs/JobDrawer.js.map +1 -1
  94. package/dist/views/Jobs/JobsTable.d.ts +4 -2
  95. package/dist/views/Jobs/JobsTable.d.ts.map +1 -1
  96. package/dist/views/Jobs/JobsTable.js +6 -5
  97. package/dist/views/Jobs/JobsTable.js.map +1 -1
  98. package/dist/views/Jobs/NewBatchJob.d.ts +34 -0
  99. package/dist/views/Jobs/NewBatchJob.d.ts.map +1 -0
  100. package/dist/views/Jobs/NewBatchJob.js +282 -0
  101. package/dist/views/Jobs/NewBatchJob.js.map +1 -0
  102. package/dist/views/Jobs/RunWithAi.d.ts +25 -0
  103. package/dist/views/Jobs/RunWithAi.d.ts.map +1 -0
  104. package/dist/views/Jobs/RunWithAi.js +46 -0
  105. package/dist/views/Jobs/RunWithAi.js.map +1 -0
  106. package/dist/views/Jobs/WorkerStrip.d.ts +3 -1
  107. package/dist/views/Jobs/WorkerStrip.d.ts.map +1 -1
  108. package/dist/views/Jobs/WorkerStrip.js +2 -2
  109. package/dist/views/Jobs/WorkerStrip.js.map +1 -1
  110. package/dist/views/Jobs/focus.d.ts +6 -0
  111. package/dist/views/Jobs/focus.d.ts.map +1 -1
  112. package/dist/views/Jobs/focus.js +10 -0
  113. package/dist/views/Jobs/focus.js.map +1 -1
  114. package/dist/views/Jobs.d.ts +14 -3
  115. package/dist/views/Jobs.d.ts.map +1 -1
  116. package/dist/views/Jobs.js +144 -32
  117. package/dist/views/Jobs.js.map +1 -1
  118. package/dist/views/MediaBrowser.d.ts +5 -1
  119. package/dist/views/MediaBrowser.d.ts.map +1 -1
  120. package/dist/views/MediaBrowser.js +6 -2
  121. package/dist/views/MediaBrowser.js.map +1 -1
  122. package/dist/views/Pages/PagesListView.d.ts +5 -1
  123. package/dist/views/Pages/PagesListView.d.ts.map +1 -1
  124. package/dist/views/Pages/PagesListView.js +7 -4
  125. package/dist/views/Pages/PagesListView.js.map +1 -1
  126. package/dist/views/Posts/PostsListView.d.ts +5 -1
  127. package/dist/views/Posts/PostsListView.d.ts.map +1 -1
  128. package/dist/views/Posts/PostsListView.js +7 -4
  129. package/dist/views/Posts/PostsListView.js.map +1 -1
  130. package/dist/views/header-footer/AnnouncementTab.d.ts +15 -0
  131. package/dist/views/header-footer/AnnouncementTab.d.ts.map +1 -0
  132. package/dist/views/header-footer/AnnouncementTab.js +43 -0
  133. package/dist/views/header-footer/AnnouncementTab.js.map +1 -0
  134. package/dist/views/header-footer/ChromeField.d.ts +25 -0
  135. package/dist/views/header-footer/ChromeField.d.ts.map +1 -0
  136. package/dist/views/header-footer/ChromeField.js +99 -0
  137. package/dist/views/header-footer/ChromeField.js.map +1 -0
  138. package/dist/views/header-footer/ChromePreview.d.ts +31 -0
  139. package/dist/views/header-footer/ChromePreview.d.ts.map +1 -0
  140. package/dist/views/header-footer/ChromePreview.js +195 -0
  141. package/dist/views/header-footer/ChromePreview.js.map +1 -0
  142. package/dist/views/header-footer/DeveloperTab.d.ts +17 -0
  143. package/dist/views/header-footer/DeveloperTab.d.ts.map +1 -0
  144. package/dist/views/header-footer/DeveloperTab.js +98 -0
  145. package/dist/views/header-footer/DeveloperTab.js.map +1 -0
  146. package/dist/views/header-footer/RegionTab.d.ts +27 -0
  147. package/dist/views/header-footer/RegionTab.d.ts.map +1 -0
  148. package/dist/views/header-footer/RegionTab.js +80 -0
  149. package/dist/views/header-footer/RegionTab.js.map +1 -0
  150. package/dist/views/header-footer/chrome-form.d.ts +137 -0
  151. package/dist/views/header-footer/chrome-form.d.ts.map +1 -0
  152. package/dist/views/header-footer/chrome-form.js +518 -0
  153. package/dist/views/header-footer/chrome-form.js.map +1 -0
  154. package/dist/views/header-footer/code-samples.d.ts +30 -0
  155. package/dist/views/header-footer/code-samples.d.ts.map +1 -0
  156. package/dist/views/header-footer/code-samples.js +127 -0
  157. package/dist/views/header-footer/code-samples.js.map +1 -0
  158. package/dist/views/header-footer/controls.d.ts +57 -0
  159. package/dist/views/header-footer/controls.d.ts.map +1 -0
  160. package/dist/views/header-footer/controls.js +43 -0
  161. package/dist/views/header-footer/controls.js.map +1 -0
  162. package/package.json +3 -3
  163. package/src/AdminRoot.tsx +36 -6
  164. package/src/__tests__/components/batch-ai-actions.test.tsx +10 -0
  165. package/src/__tests__/lib/batch-wizard.test.ts +325 -0
  166. package/src/__tests__/lib/job-drawer.test.ts +2 -0
  167. package/src/__tests__/lib/job-view.test.ts +123 -2
  168. package/src/__tests__/lib/jobs-service.test.ts +92 -3
  169. package/src/__tests__/views/appearance-chrome.render.test.tsx +818 -0
  170. package/src/__tests__/views/header-footer-form.test.ts +333 -0
  171. package/src/__tests__/views/jobs-drawer.render.test.tsx +508 -2
  172. package/src/__tests__/views/jobs-list.render.test.tsx +8 -5
  173. package/src/__tests__/views/jobs-wizard.render.test.tsx +707 -0
  174. package/src/__tests__/views/run-with-ai.render.test.tsx +807 -0
  175. package/src/components/BatchAiActions.tsx +15 -2
  176. package/src/lib/api.ts +12 -1
  177. package/src/lib/batch-wizard.ts +313 -0
  178. package/src/lib/chrome-service.ts +200 -0
  179. package/src/lib/job-view.ts +95 -1
  180. package/src/lib/jobs-service.ts +92 -1
  181. package/src/styles/prenta-tokens.css +17 -0
  182. package/src/styles/theme.css +15 -0
  183. package/src/views/AppearanceChrome.tsx +704 -46
  184. package/src/views/CollectionList.tsx +20 -1
  185. package/src/views/Jobs/CancelJobDialog.tsx +20 -2
  186. package/src/views/Jobs/DrawerOverview.tsx +16 -3
  187. package/src/views/Jobs/DrawerResults.tsx +71 -2
  188. package/src/views/Jobs/DrawerReview.tsx +1 -1
  189. package/src/views/Jobs/JobDrawer.tsx +88 -4
  190. package/src/views/Jobs/JobsTable.tsx +11 -4
  191. package/src/views/Jobs/NewBatchJob.tsx +857 -0
  192. package/src/views/Jobs/RunWithAi.tsx +89 -0
  193. package/src/views/Jobs/WorkerStrip.tsx +16 -11
  194. package/src/views/Jobs/focus.ts +11 -0
  195. package/src/views/Jobs.tsx +212 -50
  196. package/src/views/MediaBrowser.tsx +20 -1
  197. package/src/views/Pages/PagesListView.tsx +28 -3
  198. package/src/views/Posts/PostsListView.tsx +26 -3
  199. package/src/views/header-footer/AnnouncementTab.tsx +231 -0
  200. package/src/views/header-footer/ChromeField.tsx +358 -0
  201. package/src/views/header-footer/ChromePreview.tsx +497 -0
  202. package/src/views/header-footer/DeveloperTab.tsx +331 -0
  203. package/src/views/header-footer/RegionTab.tsx +398 -0
  204. package/src/views/header-footer/chrome-form.ts +603 -0
  205. package/src/views/header-footer/code-samples.ts +146 -0
  206. package/src/views/header-footer/controls.tsx +166 -0
  207. package/dist/views/Jobs/placeholders.d.ts +0 -6
  208. package/dist/views/Jobs/placeholders.d.ts.map +0 -1
  209. package/dist/views/Jobs/placeholders.js +0 -20
  210. package/dist/views/Jobs/placeholders.js.map +0 -1
  211. package/src/views/Jobs/placeholders.tsx +0 -66
@@ -13,17 +13,30 @@ const LABELS: Record<BatchOperation, string> = {
13
13
  summarize: 'Summaries',
14
14
  }
15
15
 
16
+ const ALL_OPERATIONS = Object.keys(LABELS) as BatchOperation[]
17
+
16
18
  interface BatchAiActionsProps {
17
19
  documents: Array<{ collection: string; id: string }>
18
20
  onQueued?: () => void
19
21
  buttonClassName?: string
22
+ /**
23
+ * The buttons to show, all three by default. Posts and Pages keep only
24
+ * Alt text beside "Run with AI…", whose wizard writes meta descriptions and
25
+ * excerpts but not the alt text of images inside a document (P-21).
26
+ */
27
+ operations?: readonly BatchOperation[]
20
28
  }
21
29
 
22
30
  /**
23
31
  * Queues a list-view AI batch after a confirm that names the daily cap.
24
32
  * The server writes field drafts and does not publish.
25
33
  */
26
- export function BatchAiActions({ documents, onQueued, buttonClassName }: BatchAiActionsProps) {
34
+ export function BatchAiActions({
35
+ documents,
36
+ onQueued,
37
+ buttonClassName,
38
+ operations = ALL_OPERATIONS,
39
+ }: BatchAiActionsProps) {
27
40
  const [operation, setOperation] = useState<BatchOperation | null>(null)
28
41
  const [busy, setBusy] = useState(false)
29
42
  const buttonClass =
@@ -51,7 +64,7 @@ export function BatchAiActions({ documents, onQueued, buttonClassName }: BatchAi
51
64
 
52
65
  return (
53
66
  <>
54
- {(Object.keys(LABELS) as BatchOperation[]).map((key) => (
67
+ {operations.map((key) => (
55
68
  <button
56
69
  key={key}
57
70
  type="button"
package/src/lib/api.ts CHANGED
@@ -82,6 +82,8 @@ export interface CmsApiResult<T> {
82
82
  * narrow it themselves.
83
83
  */
84
84
  body?: unknown
85
+ /** The response's `ETag`, for endpoints that take `If-Match` on the next write. */
86
+ etag?: string
85
87
  status: number
86
88
  }
87
89
 
@@ -118,6 +120,10 @@ export async function cmsApi<T = unknown>(
118
120
  const res = await fetch(url, { ...options, headers, credentials: 'include' })
119
121
  const json = await res.json().catch(() => ({}))
120
122
 
123
+ // Test doubles often stub `fetch` with a bare `{ ok, json }`.
124
+ const etag =
125
+ typeof res.headers?.get === 'function' ? (res.headers.get('ETag') ?? undefined) : undefined
126
+
121
127
  if (!res.ok) {
122
128
  return {
123
129
  error: json.error || `Request failed (${res.status})`,
@@ -127,7 +133,12 @@ export async function cmsApi<T = unknown>(
127
133
  }
128
134
  }
129
135
 
130
- return { data: json.data ?? json, body: json, status: res.status }
136
+ return {
137
+ data: json.data ?? json,
138
+ body: json,
139
+ status: res.status,
140
+ ...(etag ? { etag } : {}),
141
+ }
131
142
  } catch (err) {
132
143
  return { error: err instanceof Error ? err.message : 'Network error', status: 0 }
133
144
  }
@@ -0,0 +1,313 @@
1
+ /**
2
+ * The New batch AI job wizard (jobs-new.jsx, TRACKING P-20): its sources,
3
+ * validation and request, kept apart from the component so they can be
4
+ * tested on their own. The server's rules are in cms-core `jobs/batch-ai.ts`
5
+ * and CONFLICTS.md §4 (P-16).
6
+ */
7
+ import type {
8
+ BatchAiEstimate,
9
+ BatchAiPayload,
10
+ BatchAiRequest,
11
+ BatchAiTextField,
12
+ } from '@prenta/core'
13
+ import { JOB_OPS } from './job-view.js'
14
+ import type { SeoBatchTarget } from './jobs-service.js'
15
+
16
+ export type BatchOperation = BatchAiPayload['operation']
17
+ export type BatchOp = (typeof JOB_OPS)[number]
18
+
19
+ /** Where a batch runs: a page or post collection, or the media library. */
20
+ export interface BatchSource {
21
+ /** The collection's key in the config, or `media`. */
22
+ id: string
23
+ /** The kit's Content select label ("Posts", "Media library"). */
24
+ label: string
25
+ }
26
+
27
+ export const MEDIA_SOURCE: BatchSource = { id: 'media', label: 'Media library' }
28
+
29
+ /**
30
+ * Documents picked in a list (P-21's "Run with AI…"). They run as they are,
31
+ * without the operation's "Only where" preset.
32
+ */
33
+ export interface BatchSelection {
34
+ /** A collection key, or `media` for images picked in the media library. */
35
+ source: string
36
+ documentIds: string[]
37
+ }
38
+
39
+ /**
40
+ * What a list's "Run with AI…" sends (P-21): the picked documents, or why
41
+ * they can't run as one batch.
42
+ */
43
+ export type ListPick =
44
+ | { selection: BatchSelection; reason: null }
45
+ | { selection: null; reason: string }
46
+
47
+ /**
48
+ * The most picked documents one batch takes. The wizard's estimate sends them
49
+ * in its query string, and a request line much past 16 KB is refused; 400 ids
50
+ * is about 11 KB. Pages' grouped and tree views can select every page, so a
51
+ * pick isn't always page-sized. Fix with AI caps its batches the same way
52
+ * (cms-core `issue-batch-targets.ts`).
53
+ */
54
+ const PICK_MAX = 400
55
+
56
+ function tooMany(count: number, noun: string): ListPick | null {
57
+ if (count <= PICK_MAX) return null
58
+ return {
59
+ selection: null,
60
+ reason: `Run with AI takes at most ${PICK_MAX} ${noun} at a time. Pick fewer.`,
61
+ }
62
+ }
63
+
64
+ /** Posts and pages picked in a list. A batch runs on one collection. */
65
+ export function pickedDocuments(
66
+ picked: ReadonlyArray<{ collection: string; id: string }>,
67
+ ): ListPick {
68
+ const sources = new Set(picked.map((doc) => doc.collection))
69
+ const [source] = sources
70
+ if (sources.size > 1 || !source) {
71
+ return {
72
+ selection: null,
73
+ reason: 'Run with AI works on one post type at a time. Pick posts of a single type.',
74
+ }
75
+ }
76
+ return (
77
+ tooMany(picked.length, 'documents') ?? {
78
+ selection: { source, documentIds: picked.map((doc) => doc.id) },
79
+ reason: null,
80
+ }
81
+ )
82
+ }
83
+
84
+ /** Files picked in the media library. Only images get alt text; the rest are left out. */
85
+ export function pickedImages(imageIds: ReadonlyArray<string>): ListPick {
86
+ if (imageIds.length === 0) {
87
+ return {
88
+ selection: null,
89
+ reason: 'Run with AI writes alt text for images. Pick at least one image.',
90
+ }
91
+ }
92
+ return (
93
+ tooMany(imageIds.length, 'images') ?? {
94
+ selection: { source: MEDIA_SOURCE.id, documentIds: [...imageIds] },
95
+ reason: null,
96
+ }
97
+ )
98
+ }
99
+
100
+ /** A custom instruction needs more than 8 characters, and at most 2,000. */
101
+ const INSTRUCTION_MIN = 9
102
+ export const INSTRUCTION_MAX = 2000
103
+ /** The most documents one batch freezes. */
104
+ const BATCH_MAX = 1000
105
+
106
+ /**
107
+ * The fields a custom instruction can rewrite. `field` isn't in the kit's
108
+ * contract; it's the kit's "Field you choose" (CONFLICTS.md §4, P-16).
109
+ */
110
+ export const CUSTOM_FIELDS: ReadonlyArray<{ id: BatchAiTextField; label: string }> = [
111
+ { id: 'metaDescription', label: 'Meta description' },
112
+ { id: 'seoTitle', label: 'SEO title' },
113
+ { id: 'excerpt', label: 'Excerpt' },
114
+ ]
115
+
116
+ export function batchOp(id: BatchOperation): BatchOp {
117
+ return JOB_OPS.find((op) => op.id === id) ?? JOB_OPS[0]
118
+ }
119
+
120
+ interface ConfigCollection {
121
+ slug?: string
122
+ type?: string
123
+ labels?: { plural?: string }
124
+ admin?: { hidden?: boolean }
125
+ }
126
+
127
+ /**
128
+ * The Content select's options: the config's page and post collections, in
129
+ * config order, without hidden ones (as Settings → AI's brand voice lists
130
+ * them). The media library is added for alt text only.
131
+ */
132
+ export function batchSources(config: unknown): BatchSource[] {
133
+ const raw = (config as { collections?: unknown } | null | undefined)?.collections
134
+ if (!raw || typeof raw !== 'object') return []
135
+ const entries: Array<[string, ConfigCollection]> = Array.isArray(raw)
136
+ ? (raw as ConfigCollection[]).map((c) => [c.slug ?? '', c])
137
+ : Object.entries(raw as Record<string, ConfigCollection>)
138
+ return entries
139
+ .filter(([key, c]) => key && (c.type === 'page' || c.type === 'post') && !c.admin?.hidden)
140
+ .map(([key, c]) => ({
141
+ id: key,
142
+ label: c.labels?.plural ?? key.charAt(0).toUpperCase() + key.slice(1),
143
+ }))
144
+ }
145
+
146
+ /** cms-core's `ADMIN_ROLES`: who may queue a batch that applies changes automatically. */
147
+ export function isAdminRole(role: string | null | undefined): boolean {
148
+ return role === 'OWNER' || role === 'ADMIN'
149
+ }
150
+
151
+ /** Alt text runs on images; every other operation on a collection. */
152
+ export function runsOnMedia(operation: BatchOperation): boolean {
153
+ return operation === 'alt'
154
+ }
155
+
156
+ /** Whether an operation can run on a picked selection's source. */
157
+ export function operationFits(
158
+ operation: BatchOperation,
159
+ selection: BatchSelection | null,
160
+ ): boolean {
161
+ if (!selection) return true
162
+ return runsOnMedia(operation) === (selection.source === MEDIA_SOURCE.id)
163
+ }
164
+
165
+ /** Everything the wizard asks, before it becomes a request. */
166
+ export interface BatchDraft {
167
+ operation: BatchOperation
168
+ instruction: string
169
+ field: BatchAiTextField
170
+ /** The collection picked in the Content select (ignored for alt text). */
171
+ collection: string
172
+ statusFilter: 'published' | 'all'
173
+ review: 'review' | 'auto'
174
+ onApprove: 'draft' | 'publish'
175
+ selection: BatchSelection | null
176
+ }
177
+
178
+ /** The source a draft runs on: the media library for alt text, else its collection. */
179
+ function draftSource(draft: Pick<BatchDraft, 'operation' | 'collection'>): string {
180
+ return runsOnMedia(draft.operation) ? MEDIA_SOURCE.id : draft.collection
181
+ }
182
+
183
+ /** Step 1's check: a custom instruction needs more than 8 characters (the server's message). */
184
+ export function instructionError(operation: BatchOperation, instruction: string): string | null {
185
+ if (operation !== 'custom') return null
186
+ return instruction.trim().length < INSTRUCTION_MIN
187
+ ? 'A custom instruction needs more than 8 characters.'
188
+ : null
189
+ }
190
+
191
+ /**
192
+ * The request for estimate, preview and create. "Apply automatically" never
193
+ * publishes (the server refuses it), so it always sends `draft`.
194
+ */
195
+ export function batchRequest(draft: BatchDraft): BatchAiRequest {
196
+ const instruction = draft.instruction.trim()
197
+ return {
198
+ operation: draft.operation,
199
+ source: draft.selection?.source ?? draftSource(draft),
200
+ statusFilter: draft.statusFilter,
201
+ review: draft.review,
202
+ onApprove: draft.review === 'auto' ? 'draft' : draft.onApprove,
203
+ instruction: instruction || null,
204
+ ...(draft.operation === 'custom' ? { field: draft.field } : {}),
205
+ ...(draft.selection ? { filter: { documentIds: draft.selection.documentIds } } : {}),
206
+ }
207
+ }
208
+
209
+ /**
210
+ * The fields that change which documents match, or what the AI writes. An
211
+ * estimate or preview is stale once its key differs from the draft's.
212
+ */
213
+ export function estimateKey(request: BatchAiRequest): string {
214
+ return JSON.stringify([
215
+ request.operation,
216
+ request.source,
217
+ request.statusFilter,
218
+ request.filter?.documentIds ?? null,
219
+ ])
220
+ }
221
+
222
+ export function previewKey(request: BatchAiRequest): string {
223
+ return JSON.stringify([estimateKey(request), request.instruction, request.field ?? null])
224
+ }
225
+
226
+ /** Why step 2 can't continue: nothing matches, or more than a batch holds. Null when it can. */
227
+ export function matchProblem(estimate: BatchAiEstimate): string | null {
228
+ if (estimate.count === 0) return 'No documents match this filter.'
229
+ if (estimate.count > BATCH_MAX) {
230
+ return `This matches ${estimate.count.toLocaleString('en-US')} documents. Narrow it to ${BATCH_MAX.toLocaleString('en-US')} or fewer.`
231
+ }
232
+ return null
233
+ }
234
+
235
+ /** The estimate tiles: "~42 min" and "~38k tokens", as the kit rounds them. */
236
+ export function estimateTiles(estimate: BatchAiEstimate): { minutes: string; tokens: string } {
237
+ return {
238
+ minutes: `~${estimate.minutes.toLocaleString('en-US')} min`,
239
+ tokens: `~${Math.round(estimate.tokens / 1000).toLocaleString('en-US')}k tokens`,
240
+ }
241
+ }
242
+
243
+ /**
244
+ * The scan result category "Fix with AI" offers (jobs-drawer.jsx shows one
245
+ * box): the first, so the largest, with documents a batch can fix. Types SEO
246
+ * autopilot fixes on its own are skipped.
247
+ */
248
+ export function fixWithAiPick(
249
+ categories: ReadonlyArray<{ key: string }>,
250
+ targets: ReadonlyArray<SeoBatchTarget>,
251
+ ): SeoBatchTarget | null {
252
+ for (const category of categories) {
253
+ const target = targets.find((t) => t.type === category.key)
254
+ if (target && !target.autopilot && target.sources.length > 0) return target
255
+ }
256
+ return null
257
+ }
258
+
259
+ function plural(n: number, one: string, many = `${one}s`): string {
260
+ return `${n.toLocaleString('en-US')} ${n === 1 ? one : many}`
261
+ }
262
+
263
+ /** "Start a batch job for the 5 missing meta descriptions", per issue type. */
264
+ function fixLead(type: string, n: number): string {
265
+ const are = n === 1 ? 'is' : 'are'
266
+ if (type === 'meta-description-length') {
267
+ return `Start a batch job to shorten the ${plural(n, 'meta description')} that ${are} too long`
268
+ }
269
+ return `Start a batch job for the ${plural(n, 'missing meta description')}`
270
+ }
271
+
272
+ /**
273
+ * The "Fix with AI" box's text. The kit's is "Start a batch job for the 5
274
+ * missing meta descriptions. You’ll review each one before it’s applied.";
275
+ * this adds the content types when there are several (a batch runs on one),
276
+ * the 400 a batch takes at most, and the documents already waiting.
277
+ */
278
+ export function fixWithAiText(target: SeoBatchTarget, labelOf: (source: string) => string): string {
279
+ const total = target.sources.reduce((sum, s) => sum + s.total, 0)
280
+ const parts: string[] = []
281
+ if (target.sources.length > 1) {
282
+ const each = target.sources.map(
283
+ (s) => `${s.total.toLocaleString('en-US')} in ${labelOf(s.source)}`,
284
+ )
285
+ parts.push(
286
+ `${fixLead(target.type, total)}: ${each.slice(0, -1).join(', ')} and ${each[each.length - 1]}. A batch runs on one content type, so there’s one to set up for each.`,
287
+ )
288
+ } else {
289
+ parts.push(`${fixLead(target.type, total)}.`)
290
+ }
291
+ const capped = target.sources.find((s) => s.total > s.documentIds.length)
292
+ if (capped) {
293
+ parts.push(
294
+ `A batch takes ${capped.documentIds.length.toLocaleString('en-US')} at most, so it starts with the most recently found.`,
295
+ )
296
+ }
297
+ if (target.waiting > 0) {
298
+ parts.push(
299
+ `${plural(target.waiting, 'other')} already ${target.waiting === 1 ? 'has' : 'have'} a suggestion waiting.`,
300
+ )
301
+ }
302
+ parts.push('You’ll review each one before it’s applied.')
303
+ return parts.join(' ')
304
+ }
305
+
306
+ /** The line under the tiles. The limit sentence is left out when Settings → AI sets none. */
307
+ export function estimateNote(estimate: BatchAiEstimate): string {
308
+ const pace = 'One document per slice, about one a minute.'
309
+ const pct = estimate.pctOfMonthlyLimit
310
+ if (pct === null) return pace
311
+ const share = pct === 0 && estimate.tokens > 0 ? 'under 1' : String(pct)
312
+ return `${pace} That’s ${share}% of this month’s AI limit.`
313
+ }
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Site chrome API (DATA_CONTRACTS §2) for Appearance → Header & Footer.
3
+ * Region values and the announcement come with an `ETag`; a save sends it as
4
+ * `If-Match`, so a stale form gets 412 instead of overwriting a newer save.
5
+ */
6
+ import type {
7
+ Announcement,
8
+ ChromeOverridesList,
9
+ ChromeRegionName,
10
+ ChromeSettings,
11
+ ChromeSyncStatus,
12
+ RegionSchema,
13
+ RegionValues,
14
+ } from '@prenta/core'
15
+
16
+ import { cmsApi } from './api.js'
17
+
18
+ export interface ChromeSchemaView {
19
+ regions: RegionSchema[]
20
+ sync: ChromeSyncStatus
21
+ }
22
+
23
+ /** A result the screen can show: the value, or why there isn't one. */
24
+ export type ChromeResult<T> =
25
+ | { ok: true; value: T; etag: string | null }
26
+ | { ok: false; status: number; error: string }
27
+
28
+ function result<T>(res: {
29
+ data?: T
30
+ error?: string
31
+ status: number
32
+ etag?: string
33
+ }): ChromeResult<T> {
34
+ if (res.error !== undefined || res.data === undefined) {
35
+ return { ok: false, status: res.status, error: res.error ?? 'Request failed' }
36
+ }
37
+ return { ok: true, value: res.data, etag: res.etag ?? null }
38
+ }
39
+
40
+ function ifMatch(etag: string | null): Record<string, string> {
41
+ return etag ? { 'If-Match': etag } : {}
42
+ }
43
+
44
+ export async function fetchChromeSchema(): Promise<ChromeResult<ChromeSchemaView>> {
45
+ return result(await cmsApi<ChromeSchemaView>('/chrome/schema'))
46
+ }
47
+
48
+ /** 404 until the site has pushed the region's schema. */
49
+ export async function fetchRegion(region: ChromeRegionName): Promise<ChromeResult<RegionValues>> {
50
+ return result(await cmsApi<RegionValues>(`/chrome/${region}`))
51
+ }
52
+
53
+ /** What `PUT /chrome/:region` takes. `fields` replaces every saved value. */
54
+ export interface RegionSaveBody {
55
+ variant: string
56
+ fields: Record<string, unknown>
57
+ }
58
+
59
+ export async function saveRegion(
60
+ region: ChromeRegionName,
61
+ body: RegionSaveBody,
62
+ etag: string | null,
63
+ ): Promise<ChromeResult<RegionValues>> {
64
+ return result(
65
+ await cmsApi<RegionValues>(`/chrome/${region}`, {
66
+ method: 'PUT',
67
+ headers: ifMatch(etag),
68
+ body: JSON.stringify(body),
69
+ }),
70
+ )
71
+ }
72
+
73
+ /** "Remove now" on the orphan row. */
74
+ export async function removeOrphan(
75
+ region: ChromeRegionName,
76
+ key: string,
77
+ ): Promise<ChromeResult<RegionValues>> {
78
+ return result(
79
+ await cmsApi<RegionValues>(`/chrome/${region}/orphans/${encodeURIComponent(key)}`, {
80
+ method: 'DELETE',
81
+ }),
82
+ )
83
+ }
84
+
85
+ export async function fetchAnnouncement(): Promise<ChromeResult<Announcement>> {
86
+ return result(await cmsApi<Announcement>('/chrome/announcement'))
87
+ }
88
+
89
+ /** What `PUT /chrome/announcement` takes. The server mints `id`. */
90
+ export type AnnouncementSaveBody = Omit<Announcement, 'id'>
91
+
92
+ export async function saveAnnouncement(
93
+ body: AnnouncementSaveBody,
94
+ etag: string | null,
95
+ ): Promise<ChromeResult<Announcement>> {
96
+ return result(
97
+ await cmsApi<Announcement>('/chrome/announcement', {
98
+ method: 'PUT',
99
+ headers: ifMatch(etag),
100
+ body: JSON.stringify(body),
101
+ }),
102
+ )
103
+ }
104
+
105
+ export async function fetchChromeSettings(): Promise<ChromeResult<ChromeSettings>> {
106
+ return result(await cmsApi<ChromeSettings>('/chrome/settings'))
107
+ }
108
+
109
+ /**
110
+ * Saves the keys sent; one left out stays as it is. `secret` comes back once,
111
+ * when the save creates the revalidate webhook.
112
+ */
113
+ export async function saveChromeSettings(
114
+ body: Partial<ChromeSettings>,
115
+ ): Promise<ChromeResult<ChromeSettings & { secret?: string }>> {
116
+ return result(
117
+ await cmsApi<ChromeSettings & { secret?: string }>('/chrome/settings', {
118
+ method: 'PUT',
119
+ body: JSON.stringify(body),
120
+ }),
121
+ )
122
+ }
123
+
124
+ /** The pages whose `_layout` overrides a region. A core before 8.11 answers 404. */
125
+ export async function fetchChromeOverrides(): Promise<ChromeResult<ChromeOverridesList>> {
126
+ return result(await cmsApi<ChromeOverridesList>('/chrome/overrides'))
127
+ }
128
+
129
+ /** A menu item as the form and the preview mock read it. */
130
+ export interface ChromeMenuItem {
131
+ id: string
132
+ label: string
133
+ url: string
134
+ target?: '_blank' | '_self'
135
+ /** Shown as a button (the kit's "Show as button"). */
136
+ button: boolean
137
+ children: ChromeMenuItem[]
138
+ }
139
+
140
+ /** A menu a menu field can pick, by its slug. */
141
+ export interface ChromeMenuOption {
142
+ slug: string
143
+ name: string
144
+ items: ChromeMenuItem[]
145
+ }
146
+
147
+ function asText(value: unknown): string {
148
+ return typeof value === 'string' ? value : ''
149
+ }
150
+
151
+ function menuItems(value: unknown, depth = 0): ChromeMenuItem[] {
152
+ if (!Array.isArray(value) || depth > 6) return []
153
+ const out: ChromeMenuItem[] = []
154
+ value.forEach((raw, index) => {
155
+ if (!raw || typeof raw !== 'object') return
156
+ const item = raw as Record<string, unknown>
157
+ const label = asText(item.label).trim()
158
+ if (!label) return
159
+ out.push({
160
+ id: asText(item.id) || `${depth}-${index}`,
161
+ label,
162
+ url: asText(item.url),
163
+ ...(item.target === '_blank' || item.target === '_self' ? { target: item.target } : {}),
164
+ button: item.button === true,
165
+ children: menuItems(item.children, depth + 1),
166
+ })
167
+ })
168
+ return out
169
+ }
170
+
171
+ /**
172
+ * Menus from the navigation plugin's `navigations` collection. Without the
173
+ * plugin there are none, and menu fields offer only what's saved.
174
+ */
175
+ export async function fetchChromeMenus(): Promise<ChromeMenuOption[]> {
176
+ const res = await cmsApi<{
177
+ docs?: Array<{ slug?: string | null; title?: string | null; data?: unknown }>
178
+ }>('/collections/navigations?pageSize=100&sort=title&order=asc&pick=name,slug,items')
179
+ const menus: ChromeMenuOption[] = []
180
+ for (const doc of res.data?.docs ?? []) {
181
+ const data = (doc.data && typeof doc.data === 'object' ? doc.data : {}) as Record<
182
+ string,
183
+ unknown
184
+ >
185
+ const slug = asText(data.slug) || asText(doc.slug)
186
+ if (!slug || menus.some((menu) => menu.slug === slug)) continue
187
+ menus.push({
188
+ slug,
189
+ name: asText(data.name) || asText(doc.title) || slug,
190
+ items: menuItems(data.items),
191
+ })
192
+ }
193
+ return menus
194
+ }
195
+
196
+ /** The site title, for brand fields and the preview's logo. */
197
+ export async function fetchSiteTitle(): Promise<string | null> {
198
+ const res = await cmsApi<{ siteTitle?: string | null }>('/appearance')
199
+ return typeof res.data?.siteTitle === 'string' && res.data.siteTitle ? res.data.siteTitle : null
200
+ }