@elytracms/studio 0.0.88 → 0.0.91

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 (246) hide show
  1. package/convex/asset-revalidate.test.ts +49 -43
  2. package/convex/cms.ts +3 -4
  3. package/convex/delivery.ts +8 -11
  4. package/convex/document-revalidate.test.ts +188 -0
  5. package/convex/redirect-revalidate.test.ts +50 -37
  6. package/convex/revalidate.ts +18 -30
  7. package/convex/triggers.ts +47 -38
  8. package/convex/webhooks.ts +77 -62
  9. package/dist/components/account/self-account-view-source.js +2 -1
  10. package/dist/components/account/self-account-view-source.js.map +1 -1
  11. package/dist/components/ai/ai-chat-panel.js +1 -1
  12. package/dist/components/ai/ai-chat-panel.js.map +1 -1
  13. package/dist/components/app-views/default-modules.js +3 -3
  14. package/dist/components/app-views/default-modules.js.map +1 -1
  15. package/dist/components/assets/asset-grid.js +1 -1
  16. package/dist/components/assets/asset-grid.js.map +1 -1
  17. package/dist/components/assets/asset-selection.d.ts +8 -9
  18. package/dist/components/assets/asset-selection.js +26 -16
  19. package/dist/components/assets/asset-selection.js.map +1 -1
  20. package/dist/components/assets/assets-collection-view-source.js +3 -2
  21. package/dist/components/assets/assets-collection-view-source.js.map +1 -1
  22. package/dist/components/builder/blocks-model.d.ts +7 -5
  23. package/dist/components/builder/blocks-model.js +11 -9
  24. package/dist/components/builder/blocks-model.js.map +1 -1
  25. package/dist/components/builder/blocks-panel.js +1 -1
  26. package/dist/components/builder/blocks-panel.js.map +1 -1
  27. package/dist/components/builder/builder-store.d.ts +11 -3
  28. package/dist/components/builder/builder-store.js +12 -5
  29. package/dist/components/builder/builder-store.js.map +1 -1
  30. package/dist/components/builder/canvas-dnd.d.ts +7 -1
  31. package/dist/components/builder/canvas-dnd.js +6 -3
  32. package/dist/components/builder/canvas-dnd.js.map +1 -1
  33. package/dist/components/builder/canvas-render-context.d.ts +13 -1
  34. package/dist/components/builder/canvas-render-context.js +28 -18
  35. package/dist/components/builder/canvas-render-context.js.map +1 -1
  36. package/dist/components/builder/canvas.js +1 -1
  37. package/dist/components/builder/canvas.js.map +1 -1
  38. package/dist/components/builder/clipboard-actions.d.ts +0 -6
  39. package/dist/components/builder/clipboard-actions.js +9 -4
  40. package/dist/components/builder/clipboard-actions.js.map +1 -1
  41. package/dist/components/builder/composition-field-editor.d.ts +22 -0
  42. package/dist/components/builder/composition-field-editor.js +47 -8
  43. package/dist/components/builder/composition-field-editor.js.map +1 -1
  44. package/dist/components/builder/inline-edit.d.ts +7 -4
  45. package/dist/components/builder/inline-edit.js +11 -8
  46. package/dist/components/builder/inline-edit.js.map +1 -1
  47. package/dist/components/builder/insert-context.js +9 -5
  48. package/dist/components/builder/insert-context.js.map +1 -1
  49. package/dist/components/builder/layout-inspector.d.ts +2 -2
  50. package/dist/components/builder/layout-inspector.js +8 -6
  51. package/dist/components/builder/layout-inspector.js.map +1 -1
  52. package/dist/components/builder/node-factory.d.ts +31 -14
  53. package/dist/components/builder/node-factory.js +73 -93
  54. package/dist/components/builder/node-factory.js.map +1 -1
  55. package/dist/components/builder/page-tree.d.ts +3 -1
  56. package/dist/components/builder/page-tree.js +6 -4
  57. package/dist/components/builder/page-tree.js.map +1 -1
  58. package/dist/components/builder/property-inspector.js +2 -1
  59. package/dist/components/builder/property-inspector.js.map +1 -1
  60. package/dist/components/builder/reuse-context.js +2 -2
  61. package/dist/components/builder/reuse-context.js.map +1 -1
  62. package/dist/components/builder/reuse.d.ts +7 -3
  63. package/dist/components/builder/reuse.js +19 -11
  64. package/dist/components/builder/reuse.js.map +1 -1
  65. package/dist/components/builder/selection-overlay.d.ts +2 -2
  66. package/dist/components/builder/selection-overlay.js +3 -3
  67. package/dist/components/builder/selection-overlay.js.map +1 -1
  68. package/dist/components/builder/spacing-handles.d.ts +2 -2
  69. package/dist/components/builder/spacing-handles.js +3 -3
  70. package/dist/components/builder/spacing-handles.js.map +1 -1
  71. package/dist/components/cms/asset-field.d.ts +1 -1
  72. package/dist/components/cms/asset-field.js +15 -13
  73. package/dist/components/cms/asset-field.js.map +1 -1
  74. package/dist/components/cms/asset-picker-core.js +3 -4
  75. package/dist/components/cms/asset-picker-core.js.map +1 -1
  76. package/dist/components/cms/cell-edit.d.ts +0 -6
  77. package/dist/components/cms/cell-edit.js +5 -23
  78. package/dist/components/cms/cell-edit.js.map +1 -1
  79. package/dist/components/cms/cms-store.d.ts +3 -2
  80. package/dist/components/cms/cms-store.js +23 -24
  81. package/dist/components/cms/cms-store.js.map +1 -1
  82. package/dist/components/cms/collection-table.js +14 -4
  83. package/dist/components/cms/collection-table.js.map +1 -1
  84. package/dist/components/cms/detail-editor.js +28 -24
  85. package/dist/components/cms/detail-editor.js.map +1 -1
  86. package/dist/components/cms/discard-draft.d.ts +1 -2
  87. package/dist/components/cms/discard-draft.js +1 -1
  88. package/dist/components/cms/discard-draft.js.map +1 -1
  89. package/dist/components/cms/duplicate-document.d.ts +3 -2
  90. package/dist/components/cms/duplicate-document.js +5 -5
  91. package/dist/components/cms/duplicate-document.js.map +1 -1
  92. package/dist/components/cms/editable-cell.js +11 -7
  93. package/dist/components/cms/editable-cell.js.map +1 -1
  94. package/dist/components/cms/field-control-lib.d.ts +10 -0
  95. package/dist/components/cms/field-control-lib.js +20 -0
  96. package/dist/components/cms/field-control-lib.js.map +1 -1
  97. package/dist/components/cms/field-control.js +10 -9
  98. package/dist/components/cms/field-control.js.map +1 -1
  99. package/dist/components/cms/object-array-field.js +3 -5
  100. package/dist/components/cms/object-array-field.js.map +1 -1
  101. package/dist/components/cms/prop-fields.d.ts +16 -3
  102. package/dist/components/cms/prop-fields.js +57 -12
  103. package/dist/components/cms/prop-fields.js.map +1 -1
  104. package/dist/components/cms/publish-clean.d.ts +13 -6
  105. package/dist/components/cms/publish-clean.js +14 -6
  106. package/dist/components/cms/publish-clean.js.map +1 -1
  107. package/dist/components/cms/rich-text/embed-props.d.ts +6 -1
  108. package/dist/components/cms/rich-text/embed-props.js +7 -12
  109. package/dist/components/cms/rich-text/embed-props.js.map +1 -1
  110. package/dist/components/cms/rich-text/insert.d.ts +13 -6
  111. package/dist/components/cms/rich-text/insert.js +16 -17
  112. package/dist/components/cms/rich-text/insert.js.map +1 -1
  113. package/dist/components/cms/use-cell-edit.js +7 -12
  114. package/dist/components/cms/use-cell-edit.js.map +1 -1
  115. package/dist/components/cms/use-discard-controller.d.ts +1 -2
  116. package/dist/components/cms/use-discard-controller.js +1 -2
  117. package/dist/components/cms/use-discard-controller.js.map +1 -1
  118. package/dist/components/cms/use-publish-controller.js +3 -2
  119. package/dist/components/cms/use-publish-controller.js.map +1 -1
  120. package/dist/components/cms/versions-pane.js +2 -2
  121. package/dist/components/cms/versions-pane.js.map +1 -1
  122. package/dist/components/components/component-detail.d.ts +1 -1
  123. package/dist/components/components/component-detail.js +2 -4
  124. package/dist/components/components/component-detail.js.map +1 -1
  125. package/dist/components/components/component-preview.js +9 -4
  126. package/dist/components/components/component-preview.js.map +1 -1
  127. package/dist/components/components/components-index.d.ts +2 -2
  128. package/dist/components/components/components-index.js +3 -6
  129. package/dist/components/components/components-index.js.map +1 -1
  130. package/dist/components/components/field-inspector.js +5 -2
  131. package/dist/components/components/field-inspector.js.map +1 -1
  132. package/dist/components/components/registry-browser.d.ts +6 -5
  133. package/dist/components/components/registry-browser.js +11 -37
  134. package/dist/components/components/registry-browser.js.map +1 -1
  135. package/dist/components/components/taxonomy.d.ts +14 -21
  136. package/dist/components/components/taxonomy.js +5 -29
  137. package/dist/components/components/taxonomy.js.map +1 -1
  138. package/dist/components/components/transfer-dialog.js +1 -0
  139. package/dist/components/components/transfer-dialog.js.map +1 -1
  140. package/dist/components/components/transfer.d.ts +20 -12
  141. package/dist/components/components/transfer.js +27 -21
  142. package/dist/components/components/transfer.js.map +1 -1
  143. package/dist/components/delivery-health-banner.d.ts +3 -2
  144. package/dist/components/delivery-health-banner.js +3 -2
  145. package/dist/components/delivery-health-banner.js.map +1 -1
  146. package/dist/components/redirects/redirects-collection-view-source.js +3 -2
  147. package/dist/components/redirects/redirects-collection-view-source.js.map +1 -1
  148. package/dist/components/users/users-collection-view-source.js +2 -1
  149. package/dist/components/users/users-collection-view-source.js.map +1 -1
  150. package/dist/lib/ai/apply-content.js +32 -28
  151. package/dist/lib/ai/apply-content.js.map +1 -1
  152. package/dist/lib/ai/constraints.d.ts +16 -14
  153. package/dist/lib/ai/constraints.js +64 -48
  154. package/dist/lib/ai/constraints.js.map +1 -1
  155. package/dist/lib/ai/translate-document.js +11 -7
  156. package/dist/lib/ai/translate-document.js.map +1 -1
  157. package/dist/lib/ai/types.d.ts +9 -5
  158. package/dist/lib/ai/types.js.map +1 -1
  159. package/dist/lib/ai/update-fields.js +15 -32
  160. package/dist/lib/ai/update-fields.js.map +1 -1
  161. package/dist/lib/ai/vite.d.ts +22 -2
  162. package/dist/lib/ai/vite.js +12 -3
  163. package/dist/lib/ai/vite.js.map +1 -1
  164. package/dist/lib/assets/asset-placements.d.ts +3 -10
  165. package/dist/lib/assets/asset-placements.js +17 -8
  166. package/dist/lib/assets/asset-placements.js.map +1 -1
  167. package/dist/lib/clipboard/paste-target.js +3 -3
  168. package/dist/lib/clipboard/paste-target.js.map +1 -1
  169. package/dist/lib/cms/published-documents.d.ts +14 -3
  170. package/dist/lib/cms/published-documents.js +12 -3
  171. package/dist/lib/cms/published-documents.js.map +1 -1
  172. package/dist/lib/cms-views/view-model.d.ts +4 -4
  173. package/dist/lib/cms-views/view-model.js +26 -20
  174. package/dist/lib/cms-views/view-model.js.map +1 -1
  175. package/dist/lib/data/collection-content.d.ts +10 -7
  176. package/dist/lib/data/collection-content.js +70 -29
  177. package/dist/lib/data/collection-content.js.map +1 -1
  178. package/dist/lib/delivery/instant-publish.d.ts +0 -3
  179. package/dist/lib/delivery/instant-publish.js +0 -1
  180. package/dist/lib/delivery/instant-publish.js.map +1 -1
  181. package/dist/lib/dnd/drop-rules.d.ts +22 -7
  182. package/dist/lib/dnd/drop-rules.js +21 -14
  183. package/dist/lib/dnd/drop-rules.js.map +1 -1
  184. package/dist/lib/engine-version.d.ts +1 -1
  185. package/dist/lib/engine-version.js +1 -1
  186. package/dist/lib/engine-version.js.map +1 -1
  187. package/dist/lib/i18n/messages.de.js +25 -9
  188. package/dist/lib/i18n/messages.de.js.map +1 -1
  189. package/dist/lib/i18n/messages.en.d.ts +21 -7
  190. package/dist/lib/i18n/messages.en.js +28 -9
  191. package/dist/lib/i18n/messages.en.js.map +1 -1
  192. package/dist/lib/locale/fallback.d.ts +5 -19
  193. package/dist/lib/locale/fallback.js +18 -39
  194. package/dist/lib/locale/fallback.js.map +1 -1
  195. package/dist/lib/locale/locale-store.js +2 -1
  196. package/dist/lib/locale/locale-store.js.map +1 -1
  197. package/dist/lib/operations/cms-persistence.js +7 -4
  198. package/dist/lib/operations/cms-persistence.js.map +1 -1
  199. package/dist/lib/operations/studio-operations.js +4 -6
  200. package/dist/lib/operations/studio-operations.js.map +1 -1
  201. package/dist/lib/persistence/backend-mode.d.ts +5 -25
  202. package/dist/lib/persistence/backend-mode.js +13 -30
  203. package/dist/lib/persistence/backend-mode.js.map +1 -1
  204. package/dist/lib/persona/labels.d.ts +4 -9
  205. package/dist/lib/persona/labels.js +5 -12
  206. package/dist/lib/persona/labels.js.map +1 -1
  207. package/dist/lib/references/reference-model.d.ts +17 -5
  208. package/dist/lib/references/reference-model.js +20 -28
  209. package/dist/lib/references/reference-model.js.map +1 -1
  210. package/dist/lib/references/references-store.js +7 -0
  211. package/dist/lib/references/references-store.js.map +1 -1
  212. package/dist/lib/registry/__fixtures__/demo-components.d.ts +32 -0
  213. package/dist/lib/registry/{project-components.js → __fixtures__/demo-components.js} +18 -5
  214. package/dist/lib/registry/__fixtures__/demo-components.js.map +1 -0
  215. package/dist/lib/registry/index.d.ts +9 -13
  216. package/dist/lib/registry/index.js +34 -61
  217. package/dist/lib/registry/index.js.map +1 -1
  218. package/dist/lib/registry/preview.d.ts +22 -7
  219. package/dist/lib/registry/preview.js +26 -89
  220. package/dist/lib/registry/preview.js.map +1 -1
  221. package/dist/lib/workspace/index.d.ts +0 -7
  222. package/dist/lib/workspace/index.js +0 -9
  223. package/dist/lib/workspace/index.js.map +1 -1
  224. package/dist/previews/enumerate.d.ts +23 -27
  225. package/dist/previews/enumerate.js +27 -48
  226. package/dist/previews/enumerate.js.map +1 -1
  227. package/dist/previews/harness.js +1 -1
  228. package/dist/previews/harness.js.map +1 -1
  229. package/package.json +4 -7
  230. package/dist/lib/registry/project-components.d.ts +0 -16
  231. package/dist/lib/registry/project-components.js.map +0 -1
  232. package/dist/lib/webhooks/config.d.ts +0 -15
  233. package/dist/lib/webhooks/config.js +0 -65
  234. package/dist/lib/webhooks/config.js.map +0 -1
  235. package/dist/lib/webhooks/dispatcher.d.ts +0 -70
  236. package/dist/lib/webhooks/dispatcher.js +0 -61
  237. package/dist/lib/webhooks/dispatcher.js.map +0 -1
  238. package/dist/lib/webhooks/index.d.ts +0 -11
  239. package/dist/lib/webhooks/index.js +0 -10
  240. package/dist/lib/webhooks/index.js.map +0 -1
  241. package/dist/lib/webhooks/signing.d.ts +0 -15
  242. package/dist/lib/webhooks/signing.js +0 -24
  243. package/dist/lib/webhooks/signing.js.map +0 -1
  244. package/dist/lib/webhooks/tags.d.ts +0 -25
  245. package/dist/lib/webhooks/tags.js +0 -289
  246. package/dist/lib/webhooks/tags.js.map +0 -1
@@ -27,11 +27,14 @@ import { scheduleRevalidate } from './revalidate'
27
27
  *
28
28
  * **Which writes reach the host** — every table the delivery snapshot
29
29
  * (`delivery.ts`) projects onto the live wire is registered here, and nowhere
30
- * else decides it:
30
+ * else decides it. Since EC-579 this is the ONE revalidation emitter (the studio's
31
+ * browser dispatcher is deleted), and it sends the typed EVENT, never tags — the
32
+ * host receiver derives its own tags from it:
31
33
  *
32
- * - `cmsDocuments` — only when the live pin (`publishedVersion`) moves;
33
- * - `redirects` (EC-510) — every write (the row IS the live state);
34
- * - `assets` (EC-579) — every edit and delete; a create fires nothing.
34
+ * - `cmsDocuments` — only when the live pin (`publishedVersion`) moves
35
+ * (`publish` / `unpublish`), or a pinned row is deleted (`delete`);
36
+ * - `redirects` (EC-510) — every write (`redirects`; the row IS the live state);
37
+ * - `assets` (EC-579) — every edit and delete (`asset`); a create fires nothing.
35
38
  *
36
39
  * The snapshot reads one more table, `documentVersions`, but only the version a
37
40
  * `cmsDocuments` row pins — version rows are insert-only (`cms.ts`) and deleted
@@ -53,7 +56,7 @@ triggers.register('cmsDocuments', async (ctx, change) => {
53
56
  await removeDocumentReferences(ctx, change.oldDoc.collection, change.oldDoc.docId)
54
57
  // A published document being deleted drops out of the live site → revalidate.
55
58
  if (change.oldDoc.publishedVersion !== undefined) {
56
- await scheduleRevalidate(ctx, 'documents.delete')
59
+ await scheduleRevalidate(ctx, { kind: 'delete', collection: change.oldDoc.collection, id: change.oldDoc.docId })
57
60
  }
58
61
  return
59
62
  }
@@ -74,7 +77,11 @@ triggers.register('cmsDocuments', async (ctx, change) => {
74
77
  const before = change.oldDoc?.publishedVersion
75
78
  const after = doc.publishedVersion
76
79
  if (before !== after) {
77
- await scheduleRevalidate(ctx, after === undefined ? 'documents.unpublish' : 'documents.publish')
80
+ await scheduleRevalidate(ctx, {
81
+ kind: after === undefined ? 'unpublish' : 'publish',
82
+ collection: doc.collection,
83
+ id: doc.docId,
84
+ })
78
85
  }
79
86
  })
80
87
 
@@ -85,25 +92,28 @@ triggers.register('cmsDocuments', async (ctx, change) => {
85
92
  * — and unlike a document there is no draft/published split to gate on: the
86
93
  * write IS the live state.
87
94
  *
88
- * Why this exists at all (EC-510): the studio's browser dispatcher
89
- * (`src/lib/webhooks`) never carried the redirect operations either, so before
90
- * this a redirect change reached the host by **no** path while a document
91
- * publish reached it by two — measured 2026-08-01, five redirect writes on a
92
- * connected studio delivered zero webhooks, and a production host kept serving
93
- * the routing it had cached before the redirect existed. This trigger is the
94
- * half that catches every writer by construction (EC-286): a CLI import, a
95
- * future automation API, or any new mutation that forgets to call a helper.
95
+ * Why this exists at all (EC-510): before it, a redirect change reached the host
96
+ * by **no** path while a document publish reached it by two — measured
97
+ * 2026-08-01, five redirect writes on a connected studio delivered zero webhooks,
98
+ * and a production host kept serving the routing it had cached before the
99
+ * redirect existed. This trigger catches every writer by construction (EC-286): a
100
+ * CLI import, a future automation API, or any new mutation that forgets to call a
101
+ * helper.
96
102
  *
97
- * The tag is `scheduleRevalidate`'s whole-project sweep, which is also the right
98
- * granularity here rather than merely the available one — `ROUTING_OPERATIONS`
99
- * in `src/lib/webhooks/tags.ts` records why a targeted `route:<from>:<locale>`
100
- * tag cannot be correct. Every write fires, including a save that changed
101
- * nothing: the trigger cannot cheaply prove a no-op, and a redirect save is an
102
- * explicit editorial action, not a keystroke (EC-501's cost argument does not
103
- * transfer).
103
+ * The event is a bare `{ kind: 'redirects' }` and the receiver answers it with the
104
+ * whole-project sweep (EC-510's call, unchanged). Here — unlike in the deleted
105
+ * browser dispatcher — `change.oldDoc` does hold the previous `from`, so a
106
+ * targeted `route:<from>:<locale>` pair is obtainable in principle, but it would
107
+ * still be wrong in practice: the cached entry is tagged with the resolver's
108
+ * NORMALIZED path while `from` is editor-typed free text stored verbatim, so a
109
+ * trailing slash or a query string yields a tag that matches nothing, silently;
110
+ * and a self-hosted host honours only the sweep anyway (EC-515). Every write fires,
111
+ * including a save that changed nothing: the trigger cannot cheaply prove a
112
+ * no-op, and a redirect save is an explicit editorial action, not a keystroke
113
+ * (EC-501's cost argument does not transfer).
104
114
  */
105
- triggers.register('redirects', async (ctx, change) => {
106
- await scheduleRevalidate(ctx, change.operation === 'delete' ? 'redirects.remove' : 'redirects.save')
115
+ triggers.register('redirects', async (ctx) => {
116
+ await scheduleRevalidate(ctx, { kind: 'redirects' })
107
117
  })
108
118
 
109
119
  /**
@@ -111,21 +121,21 @@ triggers.register('redirects', async (ctx, change) => {
111
121
  * the live wire field by field (url, dimensions, alt, focal point, lqip, the
112
122
  * `meta` bag), and like a redirect there is no draft/published split: an alt,
113
123
  * focal-point or re-upload edit IS live output the moment it commits. Before
114
- * this, the only emitter for an asset edit was the studio's browser dispatcher
115
- * (`src/lib/webhooks`, active only when the studio bundle carries
116
- * `VITE_REVALIDATE_*`), so a deployment revalidating through this server path
117
- * alone — and any writer other than that browser — changed the live site
118
- * without the host ever hearing of it (EC-566 M5; measured by the Codex
124
+ * wave-0089 the only emitter for an asset edit was the studio's browser
125
+ * dispatcher (deleted by EC-579), so a deployment revalidating through this
126
+ * server path alone — and any writer other than that browser — changed the live
127
+ * site without the host ever hearing of it (EC-566 M5; measured by the Codex
119
128
  * review, P07).
120
129
  *
121
- * - **Update / delete → the whole-project sweep.** Not `asset:<id>`: the host
122
- * stamps that tag only on assets a page bakes through its composition, rich
130
+ * - **Update / delete → `{ kind: 'asset', id }`.** The receiver answers it with
131
+ * `asset:<id>` AND the whole-project sweep. The sweep is not optional: the host
132
+ * stamps `asset:<id>` only on assets a page bakes through its composition, rich
123
133
  * text or OG image (`scopeAssetsToPage` in `@elytracms/next` `route-core.ts`);
124
- * an asset read through a document asset FIELD puts no tag on the page, so a
125
- * per-asset tag would leave exactly those pages stale (EC-566 D16 / Codex F14).
126
- * The sweep tag is on every cache entry, so it is correct by construction.
127
- * - **Insert → nothing.** A brand-new asset id appears on no page yet — the
128
- * same rule the browser dispatcher applies to an `assets.upsert` create.
134
+ * an asset read through a document asset FIELD puts no tag on the page, so the
135
+ * per-asset tag alone would leave exactly those pages stale (EC-566 D16 / Codex
136
+ * F14 → EC-589). The sweep tag is on every cache entry, so it is correct by
137
+ * construction.
138
+ * - **Insert → nothing.** A brand-new asset id appears on no page yet.
129
139
  *
130
140
  * Every update fires, including one that changed nothing on the wire (the
131
141
  * editorial-only `thumb` variant, or a no-op re-save): the trigger cannot
@@ -135,10 +145,9 @@ triggers.register('redirects', async (ctx, change) => {
135
145
  * the options dialog's close, a focal-point release — not keystrokes; the one
136
146
  * bulk writer is the rail's "Generate previews" backfill, one sweep per asset.
137
147
  *
138
- * The event names are the operation names (`assets.upsert` / `assets.remove`),
139
- * matching what the browser dispatcher carries for the same writes.
148
+ * An edit and a delete are one kind: the receiver derives the same tags for both.
140
149
  */
141
150
  triggers.register('assets', async (ctx, change) => {
142
151
  if (change.operation === 'insert') return
143
- await scheduleRevalidate(ctx, change.operation === 'delete' ? 'assets.remove' : 'assets.upsert')
152
+ await scheduleRevalidate(ctx, { kind: 'asset', id: change.oldDoc.assetId })
144
153
  })
@@ -1,86 +1,101 @@
1
1
  import { internalActionGeneric } from 'convex/server'
2
2
  import { v } from 'convex/values'
3
+ import { revalidationEventSchema, signedRevalidationRequest } from '@elytracms/core/revalidation'
4
+ import type { RevalidationEvent } from '@elytracms/core/revalidation'
3
5
 
4
6
  /**
5
- * EC-146 instant publish — Convex-side webhook delivery variant.
7
+ * EC-146 instant publish — the ONE revalidation emitter's delivery half (EC-579).
6
8
  *
7
- * The v1 dispatcher (`src/lib/webhooks`) runs in the browser next to the
8
- * operations client and POSTs to the host directly (CORS + bundle-visible
9
- * secret, documented there). For Convex-backed deployments this action keeps
10
- * the secret server-side instead: the `cmsDocuments` write-chokepoint trigger
11
- * (EC-287: document publish/unpublish is the only publish path) schedules it via
12
- * `ctx.scheduler.runAfter(0, internal.webhooks.deliver, …)`
13
- * (EC-180) with the already-computed tag set, and the action signs + POSTs from
14
- * the Convex runtime. No CORS applies and the secret lives in Convex env config.
9
+ * The write-chokepoint triggers (`triggers.ts`) decide WHICH writes reach the host and
10
+ * schedule this internal action with the typed EVENT (`scheduleRevalidate`,
11
+ * `revalidate.ts`); this action signs it and POSTs it from the Convex runtime. The
12
+ * secret lives in Convex env config and never leaves the server — the studio's former
13
+ * browser dispatcher, which inlined a signing secret into the client bundle, is gone
14
+ * (EC-579 / EC-304 B-9).
15
15
  *
16
- * It is an **internal** action: only server-side callers (the scheduler) may
17
- * invoke it — a secret-signing HTTP emitter must never be client-callable.
16
+ * The webhook carries the event (`{ kind, collection?, id? }`), **not tags**: the host
17
+ * receiver derives the tags with its own scope and locales (`@elytracms/next`
18
+ * `revalidationTags`). So this deployment needs no scope of its own — the former
19
+ * `CANVAS_PROJECT_SCOPE` had to equal the host's `ELYTRA_PROJECT_ID` by hand, and when
20
+ * it did not, every sweep matched nothing, silently.
18
21
  *
19
- * Environment (set via `npx convex env set …`):
22
+ * It is an **internal** action: only server-side callers (the scheduler) may invoke it
23
+ * — a secret-signing HTTP emitter must never be client-callable.
24
+ *
25
+ * Environment (set via `npx convex env set …`, from studio/):
20
26
  * - `CANVAS_REVALIDATE_ENDPOINT` — the host's revalidate route URL
21
- * - `CANVAS_REVALIDATE_SECRET` — shared HMAC secret (= host `REVALIDATE_SECRET`)
22
- * - `CANVAS_PROJECT_SCOPE` — the host's `cache.scope` (= `ELYTRA_PROJECT_ID`),
23
- * read by the publishing mutations to scope the sweep tag (`p:<scope>:project`)
27
+ * - `CANVAS_REVALIDATE_SECRET` — shared HMAC secret (= the host's `REVALIDATE_SECRET`)
24
28
  *
25
- * Signature scheme mirrors `src/lib/webhooks/signing.ts` and is verified by
26
- * `@elytracms/next`'s `evaluateRevalidateRequest`: HMAC-SHA256 over the exact
27
- * raw JSON body, hex-encoded, sent as `x-elytra-signature: sha256=<hex>`.
28
- * Uses Web Crypto (`crypto.subtle`), which the Convex runtime provides.
29
+ * Body, signature and header come from the one wire module
30
+ * (`@elytracms/core/revalidation`), which the receiver and the doctor probe import too.
31
+ * Web Crypto only — this file has no `"use node"`, so it runs in the default runtime.
29
32
  */
30
33
 
31
- const SIGNATURE_HEADER = 'x-elytra-signature'
34
+ /** Where the webhook goes, when this deployment is configured to send one. */
35
+ export interface RevalidationTarget {
36
+ endpoint: string
37
+ secret: string
38
+ }
32
39
 
33
- function toHex(buffer: ArrayBuffer): string {
34
- return [...new Uint8Array(buffer)].map((byte) => byte.toString(16).padStart(2, '0')).join('')
40
+ /**
41
+ * The ONE reader of the instant-publish env pair. `scheduleRevalidate` asks it whether
42
+ * to schedule at all (an unconfigured deployment schedules nothing — publishing must
43
+ * never depend on a reachable host); this action asks it again for the values, since
44
+ * the env may change between the two. Blank counts as unset.
45
+ */
46
+ export function revalidationTarget(
47
+ env: Record<string, string | undefined> = (
48
+ globalThis as { process?: { env?: Record<string, string | undefined> } }
49
+ ).process?.env ?? {},
50
+ ): RevalidationTarget | undefined {
51
+ // The Convex runtime exposes deployment env vars on `process.env`; this tsconfig has
52
+ // no Node types, so the default reaches it via `globalThis`.
53
+ const endpoint = env['CANVAS_REVALIDATE_ENDPOINT']?.trim()
54
+ const secret = env['CANVAS_REVALIDATE_SECRET']?.trim()
55
+ return endpoint && secret ? { endpoint, secret } : undefined
35
56
  }
36
57
 
37
- async function signBody(rawBody: string, secret: string): Promise<string> {
38
- const encoder = new TextEncoder()
39
- const key = await crypto.subtle.importKey(
40
- 'raw',
41
- encoder.encode(secret),
42
- { name: 'HMAC', hash: 'SHA-256' },
43
- false,
44
- ['sign'],
45
- )
46
- return `sha256=${toHex(await crypto.subtle.sign('HMAC', key, encoder.encode(rawBody)))}`
58
+ /**
59
+ * Sign and POST one event — the delivery core of {@link deliver}, exported so the
60
+ * cross-party contract test sends exactly what the action sends. A non-2xx answer
61
+ * THROWS with the receiver's own message (e.g. the named "older Elytra emitter" 400
62
+ * of a version skew): the scheduled run is then marked failed and the reason is in
63
+ * the deployment's logs, instead of a `{ delivered: false }` return value nobody reads.
64
+ */
65
+ export async function deliverRevalidationEvent(
66
+ event: RevalidationEvent,
67
+ target: RevalidationTarget,
68
+ fetchImpl: typeof fetch = fetch,
69
+ ): Promise<{ delivered: true; status: number }> {
70
+ const request = await signedRevalidationRequest(event, target.secret)
71
+ const response = await fetchImpl(target.endpoint, { method: 'POST', headers: request.headers, body: request.body })
72
+ if (!response.ok) {
73
+ const answer = (await response.text().catch(() => '')).slice(0, 500)
74
+ throw new Error(
75
+ `Elytra revalidation webhook (${event.kind}) was rejected by the host with HTTP ${response.status}` +
76
+ (answer ? `: ${answer}` : '.'),
77
+ )
78
+ }
79
+ return { delivered: true, status: response.status }
47
80
  }
48
81
 
49
82
  export const deliver = internalActionGeneric({
50
83
  args: {
51
- projectId: v.string(),
52
- /** Operation name carried as the webhook `event` (e.g. `publishing.publish`). */
53
- event: v.string(),
54
- /** Fully-formatted, scoped Next tag strings (see src/lib/webhooks/tags.ts). */
55
- tags: v.array(v.string()),
84
+ /**
85
+ * The typed event (`RevalidationEvent`). `v.any()` on purpose: the event's ONE
86
+ * declaration is the zod schema in `@elytracms/core/revalidation`, parsed below —
87
+ * a hand-mirrored Convex validator would be a second declaration of the same
88
+ * shape. The only caller is `scheduleRevalidate`, which is typed by that schema.
89
+ */
90
+ event: v.any(),
56
91
  },
57
92
  handler: async (_ctx, args) => {
58
- // The Convex runtime exposes deployment env vars on `process.env`; this
59
- // tsconfig has no Node types, so reach it via `globalThis`.
60
- const env =
61
- (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {}
62
- const endpoint = env['CANVAS_REVALIDATE_ENDPOINT']
63
- const secret = env['CANVAS_REVALIDATE_SECRET']
64
- if (!endpoint || !secret) {
65
- // Unconfigured deployments are a visible no-op, never an error — local
66
- // dev must not depend on a reachable host site.
93
+ const target = revalidationTarget()
94
+ if (!target) {
95
+ // The env was unset between scheduling and running — a visible no-op, never an
96
+ // error: local dev must not depend on a reachable host site.
67
97
  return { delivered: false as const, reason: 'unconfigured' as const }
68
98
  }
69
-
70
- const rawBody = JSON.stringify({
71
- projectId: args.projectId,
72
- event: args.event,
73
- tags: args.tags,
74
- timestamp: new Date().toISOString(),
75
- })
76
- const response = await fetch(endpoint, {
77
- method: 'POST',
78
- headers: {
79
- 'content-type': 'application/json',
80
- [SIGNATURE_HEADER]: await signBody(rawBody, secret),
81
- },
82
- body: rawBody,
83
- })
84
- return { delivered: response.ok, status: response.status }
99
+ return deliverRevalidationEvent(revalidationEventSchema.parse(args.event), target)
85
100
  },
86
101
  })
@@ -5,9 +5,10 @@ import { updateProfileErrorMessageKey } from '@elytracms/studio/lib/auth-errors'
5
5
  import { useAuth } from '../auth-context.js';
6
6
  import { selfAccountCollectionDef } from './self-account-schema.js';
7
7
  import { normalizeOkResult, useRailViewSource } from '../rail-view-source.js';
8
+ import { parseLocaleConfig } from '@elytracms/core/cms-core';
8
9
  /** The account surface is not localized — one implicit locale keeps the lens honest. */
9
10
  const ACCOUNT_LOCALE = 'en';
10
- const ACCOUNT_LOCALE_CONFIG = { default: ACCOUNT_LOCALE, locales: [ACCOUNT_LOCALE] };
11
+ const ACCOUNT_LOCALE_CONFIG = parseLocaleConfig({ default: ACCOUNT_LOCALE, locales: [ACCOUNT_LOCALE] });
11
12
  /**
12
13
  * The capability profile of the account surface (EC-240 H-tail): a single self
13
14
  * record edited in place — no publish/versions/create/remove/import. The record
@@ -1 +1 @@
1
- {"version":3,"file":"self-account-view-source.js","sourceRoot":"","sources":["../../../src/components/account/self-account-view-source.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAA;AAGnC,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAA;AAMrD,OAAO,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAA;AACtD,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAA;AAChF,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAA;AACzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAA;AAChE,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAA;AAE1E,wFAAwF;AACxF,MAAM,cAAc,GAAW,IAAI,CAAA;AACnC,MAAM,qBAAqB,GAAiB,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,CAAC,cAAc,CAAC,EAAE,CAAA;AAElG;;;;GAIG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAA+B;IAC9D,OAAO,EAAE,KAAK;IACd,QAAQ,EAAE,KAAK;IACf,OAAO,EAAE,KAAK;IACd,UAAU,EAAE,KAAK;IACjB,MAAM,EAAE,KAAK;IACb,SAAS,EAAE,KAAK;IAChB,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B,EAAE,iBAAiB;QACtC,qBAAqB,EAAE,GAA0B,EAAE,CAAC,IAAI;KACzD,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import { useCallback } from 'react'\nimport type { CmsDocument, CmsValidationIssue, DocumentRef, Locale, LocaleConfig } from '@elytracms/core/cms-core'\nimport type { UserRecord } from '@elytracms/core/persistence'\nimport { studioPath } from '@elytracms/studio/router'\nimport type {\n CollectionViewCapabilities,\n CollectionViewSource,\n} from '@elytracms/studio/lib/collection-view/collection-view-source'\nimport type { OperationError } from '@elytracms/core/operations'\nimport { translate } from '@elytracms/studio/lib/i18n'\nimport { updateProfileErrorMessageKey } from '@elytracms/studio/lib/auth-errors'\nimport { useAuth } from '../auth-context'\nimport { selfAccountCollectionDef } from './self-account-schema'\nimport { normalizeOkResult, useRailViewSource } from '../rail-view-source'\n\n/** The account surface is not localized — one implicit locale keeps the lens honest. */\nconst ACCOUNT_LOCALE: Locale = 'en'\nconst ACCOUNT_LOCALE_CONFIG: LocaleConfig = { default: ACCOUNT_LOCALE, locales: [ACCOUNT_LOCALE] }\n\n/**\n * The capability profile of the account surface (EC-240 H-tail): a single self\n * record edited in place — no publish/versions/create/remove/import. The record\n * is the caller's own; there is nothing to delete or list.\n */\nexport const ACCOUNT_CAPABILITIES: CollectionViewCapabilities = {\n publish: false,\n versions: false,\n locales: false,\n inlineEdit: false,\n create: false,\n duplicate: false,\n remove: false,\n bulk: false,\n liveUrl: false,\n hierarchy: false,\n importExport: false,\n}\n\n/** Everything in `values` that is NOT an editable identity field is display-only. */\nconst EDITABLE_IDENTITY = new Set(['name', 'avatar'])\n\n/** Project the self record into the account lens's `values`. */\nexport function selfToDocument(record: UserRecord): CmsDocument {\n return {\n collection: selfAccountCollectionDef.id,\n id: record.id,\n values: {\n name: record.name ?? '',\n avatar: record.avatar ?? '',\n email: record.email,\n role: record.roles[0] ?? 'viewer',\n },\n }\n}\n\n/**\n * Compute the identity diff (name / avatar) an edited account document carries —\n * the exact seam handed to `AuthAdapter.updateProfile`. Pure so the split-write is\n * unit-testable: only the fields the person changed are sent (an empty diff is a\n * no-op the caller can short-circuit). Never carries `email`/`role` — those are\n * read-only on this surface and are not auth-adapter-writable here.\n */\nexport function accountIdentityDiff(\n doc: CmsDocument,\n previous: UserRecord,\n): { name?: string; avatar?: string } {\n const values = doc.values ?? {}\n const diff: { name?: string; avatar?: string } = {}\n const nextName = typeof values.name === 'string' ? values.name : ''\n const nextAvatar = typeof values.avatar === 'string' ? values.avatar : ''\n if (nextName !== (previous.name ?? '')) diff.name = nextName\n if (nextAvatar !== (previous.avatar ?? '')) diff.avatar = nextAvatar\n return diff\n}\n\n/**\n * Assemble a {@link CollectionViewSource} for the **account-settings** surface\n * (EC-240 H-tail). Reuses the portable edit shell over the caller's OWN record —\n * name/avatar editable, email/role read-only (per the schema). The `save` routes\n * the identity diff to `AuthAdapter.updateProfile` (auth-owned) — NOT the\n * members-rail `users.save` — then refreshes the loaded record. `EDITABLE_IDENTITY`\n * marks which fields the save may write; everything else is display-only.\n */\nexport function useSelfAccountViewSource(input: {\n projectId: string\n self: UserRecord\n refresh: () => Promise<void>\n}): CollectionViewSource {\n const { projectId, self, refresh } = input\n const auth = useAuth()\n\n const documents = useCallback(() => [selfToDocument(self)], [self])\n const get = useCallback(\n (ref: DocumentRef): CmsDocument | undefined =>\n ref.id === self.id ? selfToDocument(self) : undefined,\n [self],\n )\n const titleOf = useCallback(() => self.name || self.email || self.id, [self])\n\n const save = useCallback(\n async (doc: CmsDocument): Promise<{ ok: true } | { ok: false; message: string }> => {\n const diff = accountIdentityDiff(doc, self)\n // No identity change (e.g. a read-only-only edit) → nothing to write.\n if (diff.name === undefined && diff.avatar === undefined) return { ok: true }\n const result = await auth.updateProfile(diff)\n if (!result.ok) {\n // EC-416: engine-classified failures localize through the message\n // catalog; an unrecognized shape renders the adapter's raw English\n // message — honest, never a stale mapping (the EC-397/EC-412 pattern).\n const errorKey = updateProfileErrorMessageKey(result)\n return { ok: false, message: errorKey ? translate(errorKey) : result.message }\n }\n // Reflect the new identity in the loaded record (session already refreshed).\n await refresh()\n return { ok: true }\n },\n [auth, self, refresh],\n )\n\n const noRemove = useCallback(\n async (): Promise<{ ok: true }> => ({ ok: true }),\n [],\n )\n const noValidation = useCallback((): CmsValidationIssue[] => [], [])\n const createUnsupported = useCallback((): DocumentRef => {\n throw new Error('the account surface has no create')\n }, [])\n\n return useRailViewSource({\n projectId,\n schema: selfAccountCollectionDef,\n capabilities: ACCOUNT_CAPABILITIES,\n localeConfig: ACCOUNT_LOCALE_CONFIG,\n documents,\n get,\n titleOf,\n // Editable-identity fields drive writability; the rest are read-only per schema.\n isFieldReadOnly: (field) => !EDITABLE_IDENTITY.has(field.name) || (field.form?.readOnly ?? false),\n detailPath: (id: string) => studioPath.user(id),\n listPath: studioPath.users(),\n validate: noValidation,\n create: createUnsupported,\n save,\n remove: noRemove,\n normalizeSaveResult: normalizeOkResult,\n normalizeRemoveResult: (): OperationError | null => null,\n })\n}\n"]}
1
+ {"version":3,"file":"self-account-view-source.js","sourceRoot":"","sources":["../../../src/components/account/self-account-view-source.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAA;AAGnC,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAA;AAMrD,OAAO,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAA;AACtD,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAA;AAChF,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAA;AACzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAA;AAChE,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAA;AAC1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAA;AAE5D,wFAAwF;AACxF,MAAM,cAAc,GAAW,IAAI,CAAA;AACnC,MAAM,qBAAqB,GAAiB,iBAAiB,CAAC,EAAE,OAAO,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IAAI,EAAE,QAAQ,IAAI,KAAK,CAAC;QACjG,UAAU,EAAE,CAAC,EAAU,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QAC/C,QAAQ,EAAE,UAAU,CAAC,KAAK,EAAE;QAC5B,QAAQ,EAAE,YAAY;QACtB,MAAM,EAAE,iBAAiB;QACzB,IAAI;QACJ,MAAM,EAAE,QAAQ;QAChB,mBAAmB,EAAE,iBAAiB;QACtC,qBAAqB,EAAE,GAA0B,EAAE,CAAC,IAAI;KACzD,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import { useCallback } from 'react'\nimport type { CmsDocument, CmsValidationIssue, DocumentRef, Locale, LocaleConfig } from '@elytracms/core/cms-core'\nimport type { UserRecord } from '@elytracms/core/persistence'\nimport { studioPath } from '@elytracms/studio/router'\nimport type {\n CollectionViewCapabilities,\n CollectionViewSource,\n} from '@elytracms/studio/lib/collection-view/collection-view-source'\nimport type { OperationError } from '@elytracms/core/operations'\nimport { translate } from '@elytracms/studio/lib/i18n'\nimport { updateProfileErrorMessageKey } from '@elytracms/studio/lib/auth-errors'\nimport { useAuth } from '../auth-context'\nimport { selfAccountCollectionDef } from './self-account-schema'\nimport { normalizeOkResult, useRailViewSource } from '../rail-view-source'\nimport { parseLocaleConfig } from '@elytracms/core/cms-core'\n\n/** The account surface is not localized — one implicit locale keeps the lens honest. */\nconst ACCOUNT_LOCALE: Locale = 'en'\nconst ACCOUNT_LOCALE_CONFIG: LocaleConfig = parseLocaleConfig({ default: ACCOUNT_LOCALE, locales: [ACCOUNT_LOCALE] })\n\n/**\n * The capability profile of the account surface (EC-240 H-tail): a single self\n * record edited in place — no publish/versions/create/remove/import. The record\n * is the caller's own; there is nothing to delete or list.\n */\nexport const ACCOUNT_CAPABILITIES: CollectionViewCapabilities = {\n publish: false,\n versions: false,\n locales: false,\n inlineEdit: false,\n create: false,\n duplicate: false,\n remove: false,\n bulk: false,\n liveUrl: false,\n hierarchy: false,\n importExport: false,\n}\n\n/** Everything in `values` that is NOT an editable identity field is display-only. */\nconst EDITABLE_IDENTITY = new Set(['name', 'avatar'])\n\n/** Project the self record into the account lens's `values`. */\nexport function selfToDocument(record: UserRecord): CmsDocument {\n return {\n collection: selfAccountCollectionDef.id,\n id: record.id,\n values: {\n name: record.name ?? '',\n avatar: record.avatar ?? '',\n email: record.email,\n role: record.roles[0] ?? 'viewer',\n },\n }\n}\n\n/**\n * Compute the identity diff (name / avatar) an edited account document carries —\n * the exact seam handed to `AuthAdapter.updateProfile`. Pure so the split-write is\n * unit-testable: only the fields the person changed are sent (an empty diff is a\n * no-op the caller can short-circuit). Never carries `email`/`role` — those are\n * read-only on this surface and are not auth-adapter-writable here.\n */\nexport function accountIdentityDiff(\n doc: CmsDocument,\n previous: UserRecord,\n): { name?: string; avatar?: string } {\n const values = doc.values ?? {}\n const diff: { name?: string; avatar?: string } = {}\n const nextName = typeof values.name === 'string' ? values.name : ''\n const nextAvatar = typeof values.avatar === 'string' ? values.avatar : ''\n if (nextName !== (previous.name ?? '')) diff.name = nextName\n if (nextAvatar !== (previous.avatar ?? '')) diff.avatar = nextAvatar\n return diff\n}\n\n/**\n * Assemble a {@link CollectionViewSource} for the **account-settings** surface\n * (EC-240 H-tail). Reuses the portable edit shell over the caller's OWN record —\n * name/avatar editable, email/role read-only (per the schema). The `save` routes\n * the identity diff to `AuthAdapter.updateProfile` (auth-owned) — NOT the\n * members-rail `users.save` — then refreshes the loaded record. `EDITABLE_IDENTITY`\n * marks which fields the save may write; everything else is display-only.\n */\nexport function useSelfAccountViewSource(input: {\n projectId: string\n self: UserRecord\n refresh: () => Promise<void>\n}): CollectionViewSource {\n const { projectId, self, refresh } = input\n const auth = useAuth()\n\n const documents = useCallback(() => [selfToDocument(self)], [self])\n const get = useCallback(\n (ref: DocumentRef): CmsDocument | undefined =>\n ref.id === self.id ? selfToDocument(self) : undefined,\n [self],\n )\n const titleOf = useCallback(() => self.name || self.email || self.id, [self])\n\n const save = useCallback(\n async (doc: CmsDocument): Promise<{ ok: true } | { ok: false; message: string }> => {\n const diff = accountIdentityDiff(doc, self)\n // No identity change (e.g. a read-only-only edit) → nothing to write.\n if (diff.name === undefined && diff.avatar === undefined) return { ok: true }\n const result = await auth.updateProfile(diff)\n if (!result.ok) {\n // EC-416: engine-classified failures localize through the message\n // catalog; an unrecognized shape renders the adapter's raw English\n // message — honest, never a stale mapping (the EC-397/EC-412 pattern).\n const errorKey = updateProfileErrorMessageKey(result)\n return { ok: false, message: errorKey ? translate(errorKey) : result.message }\n }\n // Reflect the new identity in the loaded record (session already refreshed).\n await refresh()\n return { ok: true }\n },\n [auth, self, refresh],\n )\n\n const noRemove = useCallback(\n async (): Promise<{ ok: true }> => ({ ok: true }),\n [],\n )\n const noValidation = useCallback((): CmsValidationIssue[] => [], [])\n const createUnsupported = useCallback((): DocumentRef => {\n throw new Error('the account surface has no create')\n }, [])\n\n return useRailViewSource({\n projectId,\n schema: selfAccountCollectionDef,\n capabilities: ACCOUNT_CAPABILITIES,\n localeConfig: ACCOUNT_LOCALE_CONFIG,\n documents,\n get,\n titleOf,\n // Editable-identity fields drive writability; the rest are read-only per schema.\n isFieldReadOnly: (field) => !EDITABLE_IDENTITY.has(field.name) || (field.form?.readOnly ?? false),\n detailPath: (id: string) => studioPath.user(id),\n listPath: studioPath.users(),\n validate: noValidation,\n create: createUnsupported,\n save,\n remove: noRemove,\n normalizeSaveResult: normalizeOkResult,\n normalizeRemoveResult: (): OperationError | null => null,\n })\n}\n"]}
@@ -299,7 +299,7 @@ export function AiChatPanel() {
299
299
  if (projectId === undefined)
300
300
  return;
301
301
  // For an update/translate of an EXISTING document, spread the stored doc
302
- // first so document-level extras (alias, defaultLocale) survive the apply —
302
+ // first so document-level extras (the alias) survive the apply —
303
303
  // the patch replaces only values/localized.
304
304
  const existing = cms.getDocument({ collection: proposal.collection, id: proposal.documentId });
305
305
  const doc = {
@@ -1 +1 @@
1
- {"version":3,"file":"ai-chat-panel.js","sourceRoot":"","sources":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CAC7B,KAAC,aAAa,cACZ,KAAC,gBAAgB,KAAG,GACN,CACjB,CAAC,CAAC,CAAC,IAAI,EACP,MAAM,CAAC,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,CACvB,KAAC,aAAa,cACZ,KAAC,aAAa,IAAC,OAAO,EAAE,MAAM,CAAC,KAAK,GAAI,GAC1B,CACjB,CAAC,CAAC,CAAC,IAAI,IACK,EAEd,KAAK,CAAC,CAAC,CAAC,CACP,KAAC,WAAW,IAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,GAAI,CACpF,CAAC,CAAC,CAAC,CACF,cAAK,SAAS,EAAC,4BAA4B,YACzC,KAAC,IAAI,IAAC,IAAI,EAAC,IAAI,EAAC,IAAI,EAAC,OAAO,YACzB,SAAS,CAAC,sBAAsB,CAAC,GAC7B,GACH,CACP,IACK,CACT,CAAA;AACH,CAAC","sourcesContent":["import { useCallback, useMemo, useReducer, useRef, useState } from 'react'\nimport { MessageSquarePlus, X } from 'lucide-react'\nimport { DefaultChatTransport, lastAssistantMessageIsCompleteWithToolCalls } from 'ai'\nimport type { UIMessage } from 'ai'\nimport { useChat } from '@ai-sdk/react'\nimport {\n createCollectionRegistry,\n resolveDocumentTitle,\n} from '@elytracms/core/cms-core'\nimport type { CmsDocument, FieldValues } from '@elytracms/core/cms-core'\nimport { Button, Heading, Row, Spacer, Text } from '@elytracms/studio/ui'\nimport { translate } from '@elytracms/studio/lib/i18n'\nimport { STUDIO_PROJECT_ROUTE, studioPath, useNavigate } from '@elytracms/studio/router'\nimport { resolveDeploymentAi } from '@elytracms/studio/lib/workspace'\nimport { getStudioOperations } from '@elytracms/studio/lib/operations'\nimport {\n DEFAULT_MAX_STEPS,\n buildChatContext,\n chatReviewReducer,\n clearConversation,\n createChatCandidateStore,\n createChatToolExecutor,\n guardAiRouteFetch,\n initialChatReviewState,\n introducedErrors,\n isAiRouteNotMountedError,\n renderCurrentDocumentSection,\n resolveAiConfig,\n resolveChatTarget,\n resolveKnowledge,\n withStepCap,\n} from '@elytracms/studio/lib/ai'\nimport { getAiCurrentDocument } from '@elytracms/studio/lib/ai-current-document'\nimport type {\n ChatCandidateStore,\n ChatToolReaders,\n KnowledgeCollectionReader,\n ProposalReview,\n ResolvedKnowledge,\n RouteHeaders,\n} from '@elytracms/studio/lib/ai'\nimport { useCms } from '../cms/cms-store'\nimport {\n AssistantTurn,\n ChatErrorNote,\n Conversation,\n ConversationEmpty,\n PromptInput,\n ToolStatus,\n UserTurn,\n WorkingIndicator,\n describeToolPart,\n messageText,\n segmentMessageParts,\n} from './chat-ui'\nimport type { MessagePartView } from './chat-ui'\nimport { ProposalCard } from './proposal-card'\nimport { setAiPanelOpen } from '@elytracms/studio/lib/ai-panel'\n\n/**\n * The AI assistant chat panel (EC-199, moved onto the SDK's native protocol by\n * EC-334) — the right-hand collapsible surface in the CMS area. `useChat` +\n * `DefaultChatTransport` own the conversation against the route's native chat\n * branch (visible token streaming); `onToolCall` dispatches into the client\n * executor map (operations reads + terminal engines, all with the user's own\n * session); `sendAutomaticallyWhen` is the SDK predicate wrapped with the\n * per-turn step cap. What the SDK does not own lives in the pure review reducer:\n * full proposals keyed by `toolCallId` (reviewed as a diff, applied as a DRAFT\n * via operations upsert + a provenance-tagged snapshot — the EC-199 trust\n * boundary, unmoved) and blocking errors. EC-380: the \"new conversation\"\n * affordance clears busy-safely (stop → new chat id + review reset; pending\n * proposals are discarded with reject semantics).\n *\n * NEVER a modal (house rule). The whole module (including `ai` + `@ai-sdk/react`)\n * sits behind the lazy boundary (`ai-chat-panel-lazy`) — pinned in bundle tests.\n */\n\n/** Adapt a `RouteHeaders` (static or thunk) to the transport's headers resolvable. */\nfunction toTransportHeaders(headers: RouteHeaders | undefined): () => Promise<Record<string, string>> {\n return async () => {\n const resolved = typeof headers === 'function' ? await headers() : headers\n const record: Record<string, string> = {}\n new Headers(resolved ?? {}).forEach((value, key) => {\n record[key] = value\n })\n return record\n }\n}\n\nexport function AiChatPanel() {\n const cms = useCms()\n const navigate = useNavigate()\n const [review, dispatch] = useReducer(chatReviewReducer, initialChatReviewState)\n const [input, setInput] = useState('')\n // EC-380: the conversation counter — bumping it mints a fresh `useChat` id\n // (a brand-new conversation) and a fresh relation-candidate store.\n const [conversation, setConversation] = useState(1)\n\n const projectId = cms.projectId\n const activeLocale = cms.activeLocale\n\n // Resolve the AI platform config once (presence + capability gate). The panel only\n // mounts when configured, but a misconfigured provider still fails loud here.\n const resolved = useMemo(() => resolveAiConfig(resolveDeploymentAi()), [])\n const provider = resolved.resolved?.provider ?? null\n const knowledgeSources = useMemo(() => resolved.resolved?.knowledge ?? [], [resolved])\n const maxRepairAttempts = resolved.resolved?.limits?.maxRepairAttempts\n const ready = provider !== null && resolved.ok && projectId !== undefined\n\n const registry = useMemo(() => createCollectionRegistry(cms.collections), [cms.collections])\n\n /** Merge a document's non-localized + active-locale values for title/prose reads. */\n const localeValues = useCallback(\n (doc: CmsDocument): FieldValues => ({\n ...doc.values,\n ...(doc.localized?.[activeLocale] ?? {}),\n }),\n [activeLocale],\n )\n\n /** Operations-backed tool readers — client-side, with the user's own session. */\n const readers = useMemo<ChatToolReaders>(() => {\n const matches = (query: string | undefined, ...fields: (string | undefined)[]) =>\n !query || fields.some((f) => f?.toLowerCase().includes(query.toLowerCase()))\n return {\n async searchDocuments({ collection, query }) {\n if (projectId === undefined) return []\n const { operations } = await getStudioOperations()\n const result = await operations.documents.list({ projectId, collection })\n if (!result.ok) return []\n const target = cms.getCollection(collection)\n return result.value\n .map((rec) => ({\n id: rec.document.id,\n title: target\n ? resolveDocumentTitle(target, localeValues(rec.document), rec.document.id)\n : rec.document.id,\n }))\n .filter((r) => matches(query, r.title, r.id))\n },\n async listAssets({ query }) {\n if (projectId === undefined) return []\n const { operations } = await getStudioOperations()\n const result = await operations.assets.list({ projectId })\n if (!result.ok) return []\n // EC-588: the type facts ride along, so each asset field's candidates are\n // filtered by its `accept` (and the model sees what each asset is).\n return result.value\n .map((asset) => ({\n id: asset.id,\n title: asset.title ?? asset.filename,\n contentType: asset.contentType,\n filename: asset.filename,\n }))\n .filter((r) => matches(query, r.title, r.id))\n },\n // Full document (draft values + localized) — the getDocument/translate tools.\n async getDocument({ collection, id }) {\n if (projectId === undefined) return null\n const { operations } = await getStudioOperations()\n const result = await operations.documents.get({ projectId, ref: { collection, id } })\n return result.ok ? result.value?.document ?? null : null\n },\n }\n }, [projectId, cms, localeValues])\n\n /** A fresh, collision-free draft id for the target collection. */\n const mintDocumentId = useCallback(\n (collectionId: string): string => {\n const existing = new Set(cms.documentsOf(collectionId).map((d) => d.id))\n let n = 1\n while (existing.has(`new-${collectionId}-${n}`)) n += 1\n return `new-${collectionId}-${n}`\n },\n [cms],\n )\n\n /** Read `fromCollection(...)` knowledge prose through the operations layer. */\n const readCollection = useCallback<KnowledgeCollectionReader>(\n async (source) => {\n if (projectId === undefined) return []\n const { operations } = await getStudioOperations()\n const result = await operations.documents.list({ projectId, collection: source.collectionId })\n if (!result.ok) return []\n const target = cms.getCollection(source.collectionId)\n const field =\n source.field ?? target?.fields.find((f) => f.type === 'text' || f.type === 'richText')?.name\n return result.value\n .map((rec) => {\n const values = localeValues(rec.document)\n const content = field ? String(values[field] ?? '') : ''\n return { content }\n })\n .filter((item) => item.content.trim().length > 0)\n },\n [projectId, cms, localeValues],\n )\n\n // The knowledge snapshot the executors read — refreshed by the body thunk on\n // every request, so the terminal engines see what the model saw this turn.\n const knowledgeRef = useRef<ResolvedKnowledge>({ items: [] })\n\n // The chat transport target: the configured route provider's endpoint +\n // session-header thunk (EC-371), re-evaluated per request.\n const chatTarget = useMemo(() => resolveChatTarget(provider), [provider])\n\n const transport = useMemo(\n () =>\n new DefaultChatTransport({\n api: chatTarget.endpoint,\n headers: toTransportHeaders(chatTarget.headers),\n // EC-514: the same response-shape guard the structured proxy uses. Without\n // it a 200 HTML shell (route not mounted — the EC-503 dev degrade) parses\n // as an EMPTY event stream and the turn ends silently with no error at all.\n fetch: guardAiRouteFetch(),\n // The `body` THUNK — re-evaluated per request (fresh context every turn,\n // continuations included): collections-catalog summary + client-resolved\n // knowledge + EC-378's current-document block (read from the seam store\n // at REQUEST time, so every turn sees what is open NOW). The route folds\n // these sections into the system prompt; it resolves no data itself\n // (zero-data-access proxy). The block is advisory — the deterministic\n // omitted-target fallback lives in the executor.\n body: async () => {\n const knowledge = await resolveKnowledge(knowledgeSources, { readCollection })\n knowledgeRef.current = knowledge\n const current = getAiCurrentDocument()\n return {\n context: buildChatContext({\n collections: cms.collections,\n knowledge,\n ...(current\n ? {\n extraSections: [\n renderCurrentDocumentSection({\n collection: current.collection,\n id: current.id,\n title: current.title,\n locale: activeLocale,\n }),\n ],\n }\n : {}),\n }),\n }\n },\n }),\n [chatTarget, knowledgeSources, readCollection, cms.collections, activeLocale],\n )\n\n // Per-conversation relation-candidate store (EC-380: replaced on clear, so a\n // fresh conversation cannot reference the previous one's searched ids).\n const candidatesRef = useRef<{ conversation: number; store: ChatCandidateStore }>({\n conversation,\n store: createChatCandidateStore(),\n })\n if (candidatesRef.current.conversation !== conversation) {\n candidatesRef.current = { conversation, store: createChatCandidateStore() }\n }\n const candidateStore = candidatesRef.current.store\n\n const executor = useMemo(() => {\n if (!provider) return null\n return createChatToolExecutor({\n provider,\n registry,\n collections: cms.collections,\n readers,\n mintDocumentId,\n candidates: candidateStore,\n onProposal: (toolCallId, proposal) => dispatch({ type: 'propose', toolCallId, proposal }),\n knowledge: () => knowledgeRef.current,\n // EC-378: the current-document seam, read at EXECUTION time — the\n // deterministic fallback when the model omits a tool's target.\n currentDocument: () => getAiCurrentDocument(),\n locale: activeLocale,\n ...(cms.localeConfig ? { localeConfig: cms.localeConfig } : {}),\n // EC-473 established that the assistant must validate with the EDITOR's\n // rules, not a subset. EC-497 hands over THE bag itself — one value, built\n // once by `gateValidateOptions` — so the assistant's gate and the editor's\n // gate cannot drift by someone forgetting a key at a call site.\n validateOptions: cms.validateOptions,\n ...(maxRepairAttempts !== undefined ? { maxRepairAttempts } : {}),\n })\n }, [\n provider,\n registry,\n cms.collections,\n cms.localeConfig,\n cms.validateOptions,\n readers,\n mintDocumentId,\n activeLocale,\n maxRepairAttempts,\n candidateStore,\n ])\n\n const chat = useChat({\n // A new conversation is a new chat id — `useChat` recreates its state.\n id: `elytra-assistant-${conversation}`,\n transport,\n onToolCall: async ({ toolCall }) => {\n if (!executor) return\n const outcome = await executor.execute({\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input,\n })\n // Deliberately NOT awaited: `onToolCall` runs inside the chat's serial\n // stream job, and `addToolOutput` enqueues on the same executor —\n // awaiting it here deadlocks the stream (verified against ai@7.0.22).\n if (outcome.ok) {\n void chat.addToolOutput({\n tool: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n output: outcome.output,\n })\n } else {\n void chat.addToolOutput({\n state: 'output-error',\n tool: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n errorText: outcome.errorText,\n })\n }\n },\n // The SDK predicate wrapped with the per-user-turn step cap: a capped turn\n // stops cleanly with a visible note — never a silent stall (EC-334).\n sendAutomaticallyWhen: withStepCap(lastAssistantMessageIsCompleteWithToolCalls, {\n maxSteps: DEFAULT_MAX_STEPS,\n onCap: () =>\n dispatch({ type: 'fail', message: translate('ai.error.stepCap', { max: DEFAULT_MAX_STEPS }) }),\n }),\n // EC-514: \"no route mounted at <path>\" is named as itself; every other\n // transport/provider failure keeps the generic route note.\n onError: (error) =>\n dispatch({\n type: 'fail',\n message: isAiRouteNotMountedError(error)\n ? translate('ai.error.routeNotMounted', { endpoint: error.endpoint })\n : translate('ai.error.route'),\n }),\n })\n\n const busy = chat.status === 'submitted' || chat.status === 'streaming'\n\n const submit = useCallback(() => {\n const text = input.trim()\n if (text.length === 0 || busy || !ready) return\n setInput('')\n dispatch({ type: 'clear-error' })\n void chat.sendMessage({ text })\n }, [input, busy, ready, chat])\n\n // EC-380: clear / new topic — busy-safe (stop first), pending proposals\n // discarded with reject semantics (the review state resets; nothing was applied).\n const startNewConversation = useCallback(() => {\n void clearConversation({ status: chat.status, stop: chat.stop }, () => {\n dispatch({ type: 'clear' })\n setInput('')\n setConversation((current) => current + 1)\n })\n }, [chat.status, chat.stop])\n\n const applyProposal = useCallback(\n async (proposal: ProposalReview) => {\n if (projectId === undefined) return\n // For an update/translate of an EXISTING document, spread the stored doc\n // first so document-level extras (alias, defaultLocale) survive the apply —\n // the patch replaces only values/localized.\n const existing = cms.getDocument({ collection: proposal.collection, id: proposal.documentId })\n const doc: CmsDocument = {\n ...(existing ?? {}),\n collection: proposal.collection,\n id: proposal.documentId,\n values: proposal.patch.values,\n ...(proposal.patch.localized ? { localized: proposal.patch.localized } : {}),\n }\n // EC-473 — re-validate BEFORE the write. The proposal was validated when it was\n // built, but the editor may have changed the document since (or applied an\n // earlier proposal on top of it), so the patch is re-judged against what is in\n // the session NOW. Same gate as every other AI write path: only errors the\n // apply would INTRODUCE block it — pre-existing brokenness on the document is\n // not the assistant's doing and must not make an unrelated change unappliable.\n const introduced = introducedErrors(\n existing ? cms.validate(existing) : [],\n cms.validate(doc),\n )\n if (introduced.length > 0) {\n dispatch({\n type: 'fail',\n message: translate('ai.error.applyInvalid', {\n issues: introduced\n .slice(0, 3)\n .map((issue) => issue.message)\n .join('; '),\n }),\n })\n return\n }\n const { operations } = await getStudioOperations()\n const upserted = await operations.documents.upsert({ projectId, document: doc })\n if (!upserted.ok) {\n dispatch({ type: 'fail', message: translate('ai.error.applyFailed') })\n return\n }\n // Provenance: record an AI-tagged version snapshot (a restore point + the\n // 'assistant' origin surfaced in the versions pane). Best-effort — the draft\n // already landed above; a snapshot failure must not lose the applied content.\n try {\n await operations.documents.snapshot({\n projectId,\n ref: { collection: proposal.collection, id: proposal.documentId },\n label: translate('cms.version.aiAuthoredTitle'),\n origin: 'assistant',\n })\n } catch {\n // ignore — provenance is additive\n }\n // Reflect in the session so the new draft shows in the list + is navigable.\n cms.saveDocument(doc)\n // EC-378: when the applied proposal targets the document OPEN in the editor,\n // adopt it into the editor's draft buffer — otherwise the editor's autosave\n // would write its stale buffer back and silently revert the applied change.\n const current = getAiCurrentDocument()\n if (\n current &&\n current.collection === proposal.collection &&\n current.id === proposal.documentId\n ) {\n current.adoptDraft(doc)\n }\n dispatch({ type: 'apply', toolCallId: proposal.id })\n },\n [projectId, cms],\n )\n\n const openProposal = useCallback(\n (proposal: ProposalReview) => {\n if (projectId === undefined) return\n void navigate({\n to: STUDIO_PROJECT_ROUTE,\n params: { projectId, _splat: studioPath.cmsDocument(proposal.collection, proposal.documentId) },\n })\n },\n [navigate, projectId],\n )\n\n const hasProposal = useCallback(\n (toolCallId: string) => review.proposals[toolCallId] !== undefined,\n [review.proposals],\n )\n\n const renderAssistantMessage = (message: UIMessage) => {\n const segments = segmentMessageParts(message.parts as MessagePartView[], hasProposal)\n return segments.map((segment, index) => {\n if (segment.kind === 'text') {\n return (\n <AssistantTurn key={`${message.id}-${index}`}>\n <Text size=\"sm\" className=\"whitespace-pre-wrap break-words\">\n {segment.text}\n </Text>\n </AssistantTurn>\n )\n }\n if (segment.kind === 'tools') {\n return (\n <AssistantTurn key={`${message.id}-${index}`}>\n <ToolStatus steps={segment.parts.map(describeToolPart)} />\n </AssistantTurn>\n )\n }\n const proposal = review.proposals[segment.toolCallId]\n if (!proposal) return null\n return (\n <ProposalCard\n key={segment.toolCallId}\n proposal={proposal}\n onApply={() => void applyProposal(proposal)}\n onDiscard={() => dispatch({ type: 'reject', toolCallId: proposal.id })}\n onOpen={() => openProposal(proposal)}\n />\n )\n })\n }\n\n return (\n <aside className=\"flex h-full min-h-0 w-[360px] shrink-0 flex-col border-l border-border bg-card\">\n <Row gap=\"2\" align=\"center\" className=\"h-12 shrink-0 border-b border-border px-3\">\n <Heading level={2} size=\"h4\">\n {translate('ai.panel.title')}\n </Heading>\n <Spacer />\n <Button\n size=\"icon-sm\"\n variant=\"ghost\"\n onClick={startNewConversation}\n disabled={chat.messages.length === 0 && review.error === null && !busy}\n title={translate('ai.panel.newConversation')}\n aria-label={translate('ai.panel.newConversation')}\n >\n <MessageSquarePlus />\n </Button>\n <Button\n size=\"icon-sm\"\n variant=\"ghost\"\n onClick={() => setAiPanelOpen(false)}\n title={translate('ai.panel.close')}\n aria-label={translate('ai.panel.close')}\n >\n <X />\n </Button>\n </Row>\n\n <Conversation atBottomKey={chat.messages}>\n {chat.messages.length === 0 ? <ConversationEmpty /> : null}\n {chat.messages.map((message) =>\n message.role === 'user' ? (\n <UserTurn key={message.id} text={messageText(message)} />\n ) : (\n <div key={message.id} className=\"contents\">\n {renderAssistantMessage(message)}\n </div>\n ),\n )}\n {chat.status === 'submitted' ? (\n <AssistantTurn>\n <WorkingIndicator />\n </AssistantTurn>\n ) : null}\n {review.error !== null ? (\n <AssistantTurn>\n <ChatErrorNote message={review.error} />\n </AssistantTurn>\n ) : null}\n </Conversation>\n\n {ready ? (\n <PromptInput value={input} onChange={setInput} onSubmit={submit} disabled={busy} />\n ) : (\n <div className=\"border-t border-border p-3\">\n <Text size=\"xs\" tone=\"muted\">\n {translate('ai.panel.unavailable')}\n </Text>\n </div>\n )}\n </aside>\n )\n}\n"]}
1
+ {"version":3,"file":"ai-chat-panel.js","sourceRoot":"","sources":["../../../src/components/ai/ai-chat-panel.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAC1E,OAAO,EAAE,iBAAiB,EAAE,CAAC,EAAE,MAAM,cAAc,CAAA;AACnD,OAAO,EAAE,oBAAoB,EAAE,2CAA2C,EAAE,MAAM,IAAI,CAAA;AAEtF,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAA;AACvC,OAAO,EACL,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,0BAA0B,CAAA;AAEjC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,M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SAAS,EAAC,4BAA4B,YACzC,KAAC,IAAI,IAAC,IAAI,EAAC,IAAI,EAAC,IAAI,EAAC,OAAO,YACzB,SAAS,CAAC,sBAAsB,CAAC,GAC7B,GACH,CACP,IACK,CACT,CAAA;AACH,CAAC","sourcesContent":["import { useCallback, useMemo, useReducer, useRef, useState } from 'react'\nimport { MessageSquarePlus, X } from 'lucide-react'\nimport { DefaultChatTransport, lastAssistantMessageIsCompleteWithToolCalls } from 'ai'\nimport type { UIMessage } from 'ai'\nimport { useChat } from '@ai-sdk/react'\nimport {\n createCollectionRegistry,\n resolveDocumentTitle,\n} from '@elytracms/core/cms-core'\nimport type { CmsDocument, FieldValues } from '@elytracms/core/cms-core'\nimport { Button, Heading, Row, Spacer, Text } from '@elytracms/studio/ui'\nimport { translate } from '@elytracms/studio/lib/i18n'\nimport { STUDIO_PROJECT_ROUTE, studioPath, useNavigate } from '@elytracms/studio/router'\nimport { resolveDeploymentAi } from '@elytracms/studio/lib/workspace'\nimport { getStudioOperations } from '@elytracms/studio/lib/operations'\nimport {\n DEFAULT_MAX_STEPS,\n buildChatContext,\n chatReviewReducer,\n clearConversation,\n createChatCandidateStore,\n createChatToolExecutor,\n guardAiRouteFetch,\n initialChatReviewState,\n introducedErrors,\n isAiRouteNotMountedError,\n renderCurrentDocumentSection,\n resolveAiConfig,\n resolveChatTarget,\n resolveKnowledge,\n withStepCap,\n} from '@elytracms/studio/lib/ai'\nimport { getAiCurrentDocument } from '@elytracms/studio/lib/ai-current-document'\nimport type {\n ChatCandidateStore,\n ChatToolReaders,\n KnowledgeCollectionReader,\n ProposalReview,\n ResolvedKnowledge,\n RouteHeaders,\n} from '@elytracms/studio/lib/ai'\nimport { useCms } from '../cms/cms-store'\nimport {\n AssistantTurn,\n ChatErrorNote,\n Conversation,\n ConversationEmpty,\n PromptInput,\n ToolStatus,\n UserTurn,\n WorkingIndicator,\n describeToolPart,\n messageText,\n segmentMessageParts,\n} from './chat-ui'\nimport type { MessagePartView } from './chat-ui'\nimport { ProposalCard } from './proposal-card'\nimport { setAiPanelOpen } from '@elytracms/studio/lib/ai-panel'\n\n/**\n * The AI assistant chat panel (EC-199, moved onto the SDK's native protocol by\n * EC-334) — the right-hand collapsible surface in the CMS area. `useChat` +\n * `DefaultChatTransport` own the conversation against the route's native chat\n * branch (visible token streaming); `onToolCall` dispatches into the client\n * executor map (operations reads + terminal engines, all with the user's own\n * session); `sendAutomaticallyWhen` is the SDK predicate wrapped with the\n * per-turn step cap. What the SDK does not own lives in the pure review reducer:\n * full proposals keyed by `toolCallId` (reviewed as a diff, applied as a DRAFT\n * via operations upsert + a provenance-tagged snapshot — the EC-199 trust\n * boundary, unmoved) and blocking errors. EC-380: the \"new conversation\"\n * affordance clears busy-safely (stop → new chat id + review reset; pending\n * proposals are discarded with reject semantics).\n *\n * NEVER a modal (house rule). The whole module (including `ai` + `@ai-sdk/react`)\n * sits behind the lazy boundary (`ai-chat-panel-lazy`) — pinned in bundle tests.\n */\n\n/** Adapt a `RouteHeaders` (static or thunk) to the transport's headers resolvable. */\nfunction toTransportHeaders(headers: RouteHeaders | undefined): () => Promise<Record<string, string>> {\n return async () => {\n const resolved = typeof headers === 'function' ? await headers() : headers\n const record: Record<string, string> = {}\n new Headers(resolved ?? {}).forEach((value, key) => {\n record[key] = value\n })\n return record\n }\n}\n\nexport function AiChatPanel() {\n const cms = useCms()\n const navigate = useNavigate()\n const [review, dispatch] = useReducer(chatReviewReducer, initialChatReviewState)\n const [input, setInput] = useState('')\n // EC-380: the conversation counter — bumping it mints a fresh `useChat` id\n // (a brand-new conversation) and a fresh relation-candidate store.\n const [conversation, setConversation] = useState(1)\n\n const projectId = cms.projectId\n const activeLocale = cms.activeLocale\n\n // Resolve the AI platform config once (presence + capability gate). The panel only\n // mounts when configured, but a misconfigured provider still fails loud here.\n const resolved = useMemo(() => resolveAiConfig(resolveDeploymentAi()), [])\n const provider = resolved.resolved?.provider ?? null\n const knowledgeSources = useMemo(() => resolved.resolved?.knowledge ?? [], [resolved])\n const maxRepairAttempts = resolved.resolved?.limits?.maxRepairAttempts\n const ready = provider !== null && resolved.ok && projectId !== undefined\n\n const registry = useMemo(() => createCollectionRegistry(cms.collections), [cms.collections])\n\n /** Merge a document's non-localized + active-locale values for title/prose reads. */\n const localeValues = useCallback(\n (doc: CmsDocument): FieldValues => ({\n ...doc.values,\n ...(doc.localized?.[activeLocale] ?? {}),\n }),\n [activeLocale],\n )\n\n /** Operations-backed tool readers — client-side, with the user's own session. */\n const readers = useMemo<ChatToolReaders>(() => {\n const matches = (query: string | undefined, ...fields: (string | undefined)[]) =>\n !query || fields.some((f) => f?.toLowerCase().includes(query.toLowerCase()))\n return {\n async searchDocuments({ collection, query }) {\n if (projectId === undefined) return []\n const { operations } = await getStudioOperations()\n const result = await operations.documents.list({ projectId, collection })\n if (!result.ok) return []\n const target = cms.getCollection(collection)\n return result.value\n .map((rec) => ({\n id: rec.document.id,\n title: target\n ? resolveDocumentTitle(target, localeValues(rec.document), rec.document.id)\n : rec.document.id,\n }))\n .filter((r) => matches(query, r.title, r.id))\n },\n async listAssets({ query }) {\n if (projectId === undefined) return []\n const { operations } = await getStudioOperations()\n const result = await operations.assets.list({ projectId })\n if (!result.ok) return []\n // EC-588: the type facts ride along, so each asset field's candidates are\n // filtered by its `accept` (and the model sees what each asset is).\n return result.value\n .map((asset) => ({\n id: asset.id,\n title: asset.title ?? asset.filename,\n contentType: asset.contentType,\n filename: asset.filename,\n }))\n .filter((r) => matches(query, r.title, r.id))\n },\n // Full document (draft values + localized) — the getDocument/translate tools.\n async getDocument({ collection, id }) {\n if (projectId === undefined) return null\n const { operations } = await getStudioOperations()\n const result = await operations.documents.get({ projectId, ref: { collection, id } })\n return result.ok ? result.value?.document ?? null : null\n },\n }\n }, [projectId, cms, localeValues])\n\n /** A fresh, collision-free draft id for the target collection. */\n const mintDocumentId = useCallback(\n (collectionId: string): string => {\n const existing = new Set(cms.documentsOf(collectionId).map((d) => d.id))\n let n = 1\n while (existing.has(`new-${collectionId}-${n}`)) n += 1\n return `new-${collectionId}-${n}`\n },\n [cms],\n )\n\n /** Read `fromCollection(...)` knowledge prose through the operations layer. */\n const readCollection = useCallback<KnowledgeCollectionReader>(\n async (source) => {\n if (projectId === undefined) return []\n const { operations } = await getStudioOperations()\n const result = await operations.documents.list({ projectId, collection: source.collectionId })\n if (!result.ok) return []\n const target = cms.getCollection(source.collectionId)\n const field =\n source.field ?? target?.fields.find((f) => f.type === 'text' || f.type === 'richText')?.name\n return result.value\n .map((rec) => {\n const values = localeValues(rec.document)\n const content = field ? String(values[field] ?? '') : ''\n return { content }\n })\n .filter((item) => item.content.trim().length > 0)\n },\n [projectId, cms, localeValues],\n )\n\n // The knowledge snapshot the executors read — refreshed by the body thunk on\n // every request, so the terminal engines see what the model saw this turn.\n const knowledgeRef = useRef<ResolvedKnowledge>({ items: [] })\n\n // The chat transport target: the configured route provider's endpoint +\n // session-header thunk (EC-371), re-evaluated per request.\n const chatTarget = useMemo(() => resolveChatTarget(provider), [provider])\n\n const transport = useMemo(\n () =>\n new DefaultChatTransport({\n api: chatTarget.endpoint,\n headers: toTransportHeaders(chatTarget.headers),\n // EC-514: the same response-shape guard the structured proxy uses. Without\n // it a 200 HTML shell (route not mounted — the EC-503 dev degrade) parses\n // as an EMPTY event stream and the turn ends silently with no error at all.\n fetch: guardAiRouteFetch(),\n // The `body` THUNK — re-evaluated per request (fresh context every turn,\n // continuations included): collections-catalog summary + client-resolved\n // knowledge + EC-378's current-document block (read from the seam store\n // at REQUEST time, so every turn sees what is open NOW). The route folds\n // these sections into the system prompt; it resolves no data itself\n // (zero-data-access proxy). The block is advisory — the deterministic\n // omitted-target fallback lives in the executor.\n body: async () => {\n const knowledge = await resolveKnowledge(knowledgeSources, { readCollection })\n knowledgeRef.current = knowledge\n const current = getAiCurrentDocument()\n return {\n context: buildChatContext({\n collections: cms.collections,\n knowledge,\n ...(current\n ? {\n extraSections: [\n renderCurrentDocumentSection({\n collection: current.collection,\n id: current.id,\n title: current.title,\n locale: activeLocale,\n }),\n ],\n }\n : {}),\n }),\n }\n },\n }),\n [chatTarget, knowledgeSources, readCollection, cms.collections, activeLocale],\n )\n\n // Per-conversation relation-candidate store (EC-380: replaced on clear, so a\n // fresh conversation cannot reference the previous one's searched ids).\n const candidatesRef = useRef<{ conversation: number; store: ChatCandidateStore }>({\n conversation,\n store: createChatCandidateStore(),\n })\n if (candidatesRef.current.conversation !== conversation) {\n candidatesRef.current = { conversation, store: createChatCandidateStore() }\n }\n const candidateStore = candidatesRef.current.store\n\n const executor = useMemo(() => {\n if (!provider) return null\n return createChatToolExecutor({\n provider,\n registry,\n collections: cms.collections,\n readers,\n mintDocumentId,\n candidates: candidateStore,\n onProposal: (toolCallId, proposal) => dispatch({ type: 'propose', toolCallId, proposal }),\n knowledge: () => knowledgeRef.current,\n // EC-378: the current-document seam, read at EXECUTION time — the\n // deterministic fallback when the model omits a tool's target.\n currentDocument: () => getAiCurrentDocument(),\n locale: activeLocale,\n ...(cms.localeConfig ? { localeConfig: cms.localeConfig } : {}),\n // EC-473 established that the assistant must validate with the EDITOR's\n // rules, not a subset. EC-497 hands over THE bag itself — one value, built\n // once by `gateValidateOptions` — so the assistant's gate and the editor's\n // gate cannot drift by someone forgetting a key at a call site.\n validateOptions: cms.validateOptions,\n ...(maxRepairAttempts !== undefined ? { maxRepairAttempts } : {}),\n })\n }, [\n provider,\n registry,\n cms.collections,\n cms.localeConfig,\n cms.validateOptions,\n readers,\n mintDocumentId,\n activeLocale,\n maxRepairAttempts,\n candidateStore,\n ])\n\n const chat = useChat({\n // A new conversation is a new chat id — `useChat` recreates its state.\n id: `elytra-assistant-${conversation}`,\n transport,\n onToolCall: async ({ toolCall }) => {\n if (!executor) return\n const outcome = await executor.execute({\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input,\n })\n // Deliberately NOT awaited: `onToolCall` runs inside the chat's serial\n // stream job, and `addToolOutput` enqueues on the same executor —\n // awaiting it here deadlocks the stream (verified against ai@7.0.22).\n if (outcome.ok) {\n void chat.addToolOutput({\n tool: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n output: outcome.output,\n })\n } else {\n void chat.addToolOutput({\n state: 'output-error',\n tool: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n errorText: outcome.errorText,\n })\n }\n },\n // The SDK predicate wrapped with the per-user-turn step cap: a capped turn\n // stops cleanly with a visible note — never a silent stall (EC-334).\n sendAutomaticallyWhen: withStepCap(lastAssistantMessageIsCompleteWithToolCalls, {\n maxSteps: DEFAULT_MAX_STEPS,\n onCap: () =>\n dispatch({ type: 'fail', message: translate('ai.error.stepCap', { max: DEFAULT_MAX_STEPS }) }),\n }),\n // EC-514: \"no route mounted at <path>\" is named as itself; every other\n // transport/provider failure keeps the generic route note.\n onError: (error) =>\n dispatch({\n type: 'fail',\n message: isAiRouteNotMountedError(error)\n ? translate('ai.error.routeNotMounted', { endpoint: error.endpoint })\n : translate('ai.error.route'),\n }),\n })\n\n const busy = chat.status === 'submitted' || chat.status === 'streaming'\n\n const submit = useCallback(() => {\n const text = input.trim()\n if (text.length === 0 || busy || !ready) return\n setInput('')\n dispatch({ type: 'clear-error' })\n void chat.sendMessage({ text })\n }, [input, busy, ready, chat])\n\n // EC-380: clear / new topic — busy-safe (stop first), pending proposals\n // discarded with reject semantics (the review state resets; nothing was applied).\n const startNewConversation = useCallback(() => {\n void clearConversation({ status: chat.status, stop: chat.stop }, () => {\n dispatch({ type: 'clear' })\n setInput('')\n setConversation((current) => current + 1)\n })\n }, [chat.status, chat.stop])\n\n const applyProposal = useCallback(\n async (proposal: ProposalReview) => {\n if (projectId === undefined) return\n // For an update/translate of an EXISTING document, spread the stored doc\n // first so document-level extras (the alias) survive the apply —\n // the patch replaces only values/localized.\n const existing = cms.getDocument({ collection: proposal.collection, id: proposal.documentId })\n const doc: CmsDocument = {\n ...(existing ?? {}),\n collection: proposal.collection,\n id: proposal.documentId,\n values: proposal.patch.values,\n ...(proposal.patch.localized ? { localized: proposal.patch.localized } : {}),\n }\n // EC-473 — re-validate BEFORE the write. The proposal was validated when it was\n // built, but the editor may have changed the document since (or applied an\n // earlier proposal on top of it), so the patch is re-judged against what is in\n // the session NOW. Same gate as every other AI write path: only errors the\n // apply would INTRODUCE block it — pre-existing brokenness on the document is\n // not the assistant's doing and must not make an unrelated change unappliable.\n const introduced = introducedErrors(\n existing ? cms.validate(existing) : [],\n cms.validate(doc),\n )\n if (introduced.length > 0) {\n dispatch({\n type: 'fail',\n message: translate('ai.error.applyInvalid', {\n issues: introduced\n .slice(0, 3)\n .map((issue) => issue.message)\n .join('; '),\n }),\n })\n return\n }\n const { operations } = await getStudioOperations()\n const upserted = await operations.documents.upsert({ projectId, document: doc })\n if (!upserted.ok) {\n dispatch({ type: 'fail', message: translate('ai.error.applyFailed') })\n return\n }\n // Provenance: record an AI-tagged version snapshot (a restore point + the\n // 'assistant' origin surfaced in the versions pane). Best-effort — the draft\n // already landed above; a snapshot failure must not lose the applied content.\n try {\n await operations.documents.snapshot({\n projectId,\n ref: { collection: proposal.collection, id: proposal.documentId },\n label: translate('cms.version.aiAuthoredTitle'),\n origin: 'assistant',\n })\n } catch {\n // ignore — provenance is additive\n }\n // Reflect in the session so the new draft shows in the list + is navigable.\n cms.saveDocument(doc)\n // EC-378: when the applied proposal targets the document OPEN in the editor,\n // adopt it into the editor's draft buffer — otherwise the editor's autosave\n // would write its stale buffer back and silently revert the applied change.\n const current = getAiCurrentDocument()\n if (\n current &&\n current.collection === proposal.collection &&\n current.id === proposal.documentId\n ) {\n current.adoptDraft(doc)\n }\n dispatch({ type: 'apply', toolCallId: proposal.id })\n },\n [projectId, cms],\n )\n\n const openProposal = useCallback(\n (proposal: ProposalReview) => {\n if (projectId === undefined) return\n void navigate({\n to: STUDIO_PROJECT_ROUTE,\n params: { projectId, _splat: studioPath.cmsDocument(proposal.collection, proposal.documentId) },\n })\n },\n [navigate, projectId],\n )\n\n const hasProposal = useCallback(\n (toolCallId: string) => review.proposals[toolCallId] !== undefined,\n [review.proposals],\n )\n\n const renderAssistantMessage = (message: UIMessage) => {\n const segments = segmentMessageParts(message.parts as MessagePartView[], hasProposal)\n return segments.map((segment, index) => {\n if (segment.kind === 'text') {\n return (\n <AssistantTurn key={`${message.id}-${index}`}>\n <Text size=\"sm\" className=\"whitespace-pre-wrap break-words\">\n {segment.text}\n </Text>\n </AssistantTurn>\n )\n }\n if (segment.kind === 'tools') {\n return (\n <AssistantTurn key={`${message.id}-${index}`}>\n <ToolStatus steps={segment.parts.map(describeToolPart)} />\n </AssistantTurn>\n )\n }\n const proposal = review.proposals[segment.toolCallId]\n if (!proposal) return null\n return (\n <ProposalCard\n key={segment.toolCallId}\n proposal={proposal}\n onApply={() => void applyProposal(proposal)}\n onDiscard={() => dispatch({ type: 'reject', toolCallId: proposal.id })}\n onOpen={() => openProposal(proposal)}\n />\n )\n })\n }\n\n return (\n <aside className=\"flex h-full min-h-0 w-[360px] shrink-0 flex-col border-l border-border bg-card\">\n <Row gap=\"2\" align=\"center\" className=\"h-12 shrink-0 border-b border-border px-3\">\n <Heading level={2} size=\"h4\">\n {translate('ai.panel.title')}\n </Heading>\n <Spacer />\n <Button\n size=\"icon-sm\"\n variant=\"ghost\"\n onClick={startNewConversation}\n disabled={chat.messages.length === 0 && review.error === null && !busy}\n title={translate('ai.panel.newConversation')}\n aria-label={translate('ai.panel.newConversation')}\n >\n <MessageSquarePlus />\n </Button>\n <Button\n size=\"icon-sm\"\n variant=\"ghost\"\n onClick={() => setAiPanelOpen(false)}\n title={translate('ai.panel.close')}\n aria-label={translate('ai.panel.close')}\n >\n <X />\n </Button>\n </Row>\n\n <Conversation atBottomKey={chat.messages}>\n {chat.messages.length === 0 ? <ConversationEmpty /> : null}\n {chat.messages.map((message) =>\n message.role === 'user' ? (\n <UserTurn key={message.id} text={messageText(message)} />\n ) : (\n <div key={message.id} className=\"contents\">\n {renderAssistantMessage(message)}\n </div>\n ),\n )}\n {chat.status === 'submitted' ? (\n <AssistantTurn>\n <WorkingIndicator />\n </AssistantTurn>\n ) : null}\n {review.error !== null ? (\n <AssistantTurn>\n <ChatErrorNote message={review.error} />\n </AssistantTurn>\n ) : null}\n </Conversation>\n\n {ready ? (\n <PromptInput value={input} onChange={setInput} onSubmit={submit} disabled={busy} />\n ) : (\n <div className=\"border-t border-border p-3\">\n <Text size=\"xs\" tone=\"muted\">\n {translate('ai.panel.unavailable')}\n </Text>\n </div>\n )}\n </aside>\n )\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useEffect } from 'react';
3
3
  import { Blocks, Database, FileCog, Image, LayoutGrid, Settings as SettingsIcon, Signpost, Users, } from 'lucide-react';
4
- import { assetCollection, extendCollectionDef, isSingleton, resolveSingletonDocument, } from '@elytracms/core/cms-core';
4
+ import { assetCollection, extendCollectionDef, isSingleton, parseLocaleConfig, resolveSingletonDocument, } from '@elytracms/core/cms-core';
5
5
  import { NavigateOnce, STUDIO_PROJECT_ROUTE, studioPath } from '@elytracms/studio/router';
6
6
  import { Text } from '@elytracms/studio/ui';
7
7
  import { localizedLabel, translate } from '@elytracms/studio/lib/i18n';
@@ -577,10 +577,10 @@ export function resolveCmsInitialDocuments(cms) {
577
577
  export function resolveCmsInitialLocaleConfig(_cms, project, configLocales = resolveDeploymentLocaleConfig()) {
578
578
  if (configLocales)
579
579
  return configLocales;
580
- return {
580
+ return parseLocaleConfig({
581
581
  default: project.settings.defaultLocale,
582
582
  locales: [...project.settings.locales],
583
- };
583
+ });
584
584
  }
585
585
  /**
586
586
  * CMS section: hydrates the persisted (or kit-seeded) collections + documents, then