@elytracms/studio 0.0.85 → 0.0.87

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 (248) hide show
  1. package/convex/asset-revalidate.test.ts +186 -0
  2. package/convex/assets.ts +53 -19
  3. package/convex/cms.ts +22 -0
  4. package/convex/delivery.ts +54 -116
  5. package/convex/engine-version.test.ts +31 -0
  6. package/convex/functions.ts +3 -3
  7. package/convex/rail-write-parity.test.ts +180 -0
  8. package/convex/redirects.ts +33 -11
  9. package/convex/revalidate.ts +7 -5
  10. package/convex/triggers.ts +53 -3
  11. package/dist/components/ai/ai-chat-panel.js +13 -2
  12. package/dist/components/ai/ai-chat-panel.js.map +1 -1
  13. package/dist/components/app-views/default-modules.d.ts +20 -20
  14. package/dist/components/app-views/default-modules.js +27 -48
  15. package/dist/components/app-views/default-modules.js.map +1 -1
  16. package/dist/components/app-views/studio-config.d.ts +5 -6
  17. package/dist/components/app-views/studio-config.js.map +1 -1
  18. package/dist/components/assets/asset-metadata.d.ts +28 -19
  19. package/dist/components/assets/asset-metadata.js +24 -31
  20. package/dist/components/assets/asset-metadata.js.map +1 -1
  21. package/dist/components/assets/asset-selection.d.ts +24 -5
  22. package/dist/components/assets/asset-selection.js +39 -9
  23. package/dist/components/assets/asset-selection.js.map +1 -1
  24. package/dist/components/assets/assets-collection-view-source.d.ts +17 -14
  25. package/dist/components/assets/assets-collection-view-source.js +25 -31
  26. package/dist/components/assets/assets-collection-view-source.js.map +1 -1
  27. package/dist/components/builder/blocks-model.d.ts +5 -4
  28. package/dist/components/builder/blocks-model.js +5 -4
  29. package/dist/components/builder/blocks-model.js.map +1 -1
  30. package/dist/components/builder/blocks-panel.js +3 -3
  31. package/dist/components/builder/blocks-panel.js.map +1 -1
  32. package/dist/components/builder/builder-store.d.ts +25 -1
  33. package/dist/components/builder/builder-store.js +3 -2
  34. package/dist/components/builder/builder-store.js.map +1 -1
  35. package/dist/components/builder/canvas-chrome-css.js +0 -17
  36. package/dist/components/builder/canvas-chrome-css.js.map +1 -1
  37. package/dist/components/builder/canvas-chrome.d.ts +10 -12
  38. package/dist/components/builder/canvas-chrome.js +12 -13
  39. package/dist/components/builder/canvas-chrome.js.map +1 -1
  40. package/dist/components/builder/canvas-dnd.d.ts +8 -0
  41. package/dist/components/builder/canvas-dnd.js +5 -3
  42. package/dist/components/builder/canvas-dnd.js.map +1 -1
  43. package/dist/components/builder/canvas-render-context.d.ts +12 -24
  44. package/dist/components/builder/canvas-render-context.js +15 -44
  45. package/dist/components/builder/canvas-render-context.js.map +1 -1
  46. package/dist/components/builder/canvas.js +5 -11
  47. package/dist/components/builder/canvas.js.map +1 -1
  48. package/dist/components/builder/clipboard-actions.d.ts +15 -1
  49. package/dist/components/builder/clipboard-actions.js +35 -12
  50. package/dist/components/builder/clipboard-actions.js.map +1 -1
  51. package/dist/components/builder/composition-field-editor.d.ts +32 -26
  52. package/dist/components/builder/composition-field-editor.js +47 -54
  53. package/dist/components/builder/composition-field-editor.js.map +1 -1
  54. package/dist/components/builder/insert-context.d.ts +3 -1
  55. package/dist/components/builder/insert-context.js +19 -12
  56. package/dist/components/builder/insert-context.js.map +1 -1
  57. package/dist/components/builder/page-tree.d.ts +29 -0
  58. package/dist/components/builder/page-tree.js +56 -58
  59. package/dist/components/builder/page-tree.js.map +1 -1
  60. package/dist/components/builder/reuse.js +5 -2
  61. package/dist/components/builder/reuse.js.map +1 -1
  62. package/dist/components/cms/asset-field.js +20 -32
  63. package/dist/components/cms/asset-field.js.map +1 -1
  64. package/dist/components/cms/cell-edit.d.ts +7 -0
  65. package/dist/components/cms/cell-edit.js +9 -1
  66. package/dist/components/cms/cell-edit.js.map +1 -1
  67. package/dist/components/cms/cms-composition-validators.js +11 -2
  68. package/dist/components/cms/cms-composition-validators.js.map +1 -1
  69. package/dist/components/cms/collection-table.js +11 -0
  70. package/dist/components/cms/collection-table.js.map +1 -1
  71. package/dist/components/cms/document-url-path.d.ts +7 -4
  72. package/dist/components/cms/document-url-path.js +15 -1
  73. package/dist/components/cms/document-url-path.js.map +1 -1
  74. package/dist/components/cms/editable-cell.js +5 -2
  75. package/dist/components/cms/editable-cell.js.map +1 -1
  76. package/dist/components/cms/field-control.js +4 -0
  77. package/dist/components/cms/field-control.js.map +1 -1
  78. package/dist/components/cms/inline-field-errors.d.ts +36 -0
  79. package/dist/components/cms/inline-field-errors.js +13 -5
  80. package/dist/components/cms/inline-field-errors.js.map +1 -1
  81. package/dist/components/cms/rich-text/insert.d.ts +6 -3
  82. package/dist/components/cms/rich-text/insert.js +9 -6
  83. package/dist/components/cms/rich-text/insert.js.map +1 -1
  84. package/dist/components/cms/use-document-versions.js +1 -0
  85. package/dist/components/cms/use-document-versions.js.map +1 -1
  86. package/dist/components/cms/use-live-url.d.ts +18 -6
  87. package/dist/components/cms/use-live-url.js +10 -0
  88. package/dist/components/cms/use-live-url.js.map +1 -1
  89. package/dist/components/cms/versions-model.d.ts +0 -12
  90. package/dist/components/cms/versions-model.js +3 -15
  91. package/dist/components/cms/versions-model.js.map +1 -1
  92. package/dist/components/components/component-detail.js +1 -1
  93. package/dist/components/components/component-detail.js.map +1 -1
  94. package/dist/components/components/transfer-dialog.js +2 -4
  95. package/dist/components/components/transfer-dialog.js.map +1 -1
  96. package/dist/components/components/transfer.d.ts +19 -15
  97. package/dist/components/components/transfer.js +28 -25
  98. package/dist/components/components/transfer.js.map +1 -1
  99. package/dist/components/deployment-setup-gate.js +9 -3
  100. package/dist/components/deployment-setup-gate.js.map +1 -1
  101. package/dist/components/project-session.d.ts +9 -0
  102. package/dist/components/project-session.js +1 -1
  103. package/dist/components/project-session.js.map +1 -1
  104. package/dist/components/redirects/redirects-collection-view-source.d.ts +17 -2
  105. package/dist/components/redirects/redirects-collection-view-source.js +20 -6
  106. package/dist/components/redirects/redirects-collection-view-source.js.map +1 -1
  107. package/dist/components/section-surface.js +3 -2
  108. package/dist/components/section-surface.js.map +1 -1
  109. package/dist/components/settings-form.js +1 -2
  110. package/dist/components/settings-form.js.map +1 -1
  111. package/dist/components/studio-context.js +1 -18
  112. package/dist/components/studio-context.js.map +1 -1
  113. package/dist/components/studio-project-screen.js +3 -5
  114. package/dist/components/studio-project-screen.js.map +1 -1
  115. package/dist/lib/ai/apply-content.js +73 -29
  116. package/dist/lib/ai/apply-content.js.map +1 -1
  117. package/dist/lib/ai/constraints.d.ts +35 -0
  118. package/dist/lib/ai/constraints.js +155 -72
  119. package/dist/lib/ai/constraints.js.map +1 -1
  120. package/dist/lib/ai/index.d.ts +1 -0
  121. package/dist/lib/ai/index.js +1 -0
  122. package/dist/lib/ai/index.js.map +1 -1
  123. package/dist/lib/ai/route-fetch.d.ts +58 -0
  124. package/dist/lib/ai/route-fetch.js +98 -0
  125. package/dist/lib/ai/route-fetch.js.map +1 -0
  126. package/dist/lib/ai/route-provider.d.ts +5 -22
  127. package/dist/lib/ai/route-provider.js +23 -1
  128. package/dist/lib/ai/route-provider.js.map +1 -1
  129. package/dist/lib/ai/route.js +4 -1
  130. package/dist/lib/ai/route.js.map +1 -1
  131. package/dist/lib/ai/shape.d.ts +3 -2
  132. package/dist/lib/ai/shape.js +16 -24
  133. package/dist/lib/ai/shape.js.map +1 -1
  134. package/dist/lib/ai/types.d.ts +8 -0
  135. package/dist/lib/ai/types.js.map +1 -1
  136. package/dist/lib/ai/update-fields.js +33 -12
  137. package/dist/lib/ai/update-fields.js.map +1 -1
  138. package/dist/lib/assets/asset-placements.d.ts +35 -0
  139. package/dist/lib/assets/asset-placements.js +74 -0
  140. package/dist/lib/assets/asset-placements.js.map +1 -0
  141. package/dist/lib/assets/backfill-thumbs.d.ts +9 -8
  142. package/dist/lib/assets/backfill-thumbs.js +13 -25
  143. package/dist/lib/assets/backfill-thumbs.js.map +1 -1
  144. package/dist/lib/clipboard/paste-issues.d.ts +17 -15
  145. package/dist/lib/clipboard/paste-issues.js +8 -45
  146. package/dist/lib/clipboard/paste-issues.js.map +1 -1
  147. package/dist/lib/clipboard/paste-target.d.ts +47 -1
  148. package/dist/lib/clipboard/paste-target.js +19 -11
  149. package/dist/lib/clipboard/paste-target.js.map +1 -1
  150. package/dist/lib/cms/document-gate.d.ts +19 -9
  151. package/dist/lib/cms/document-gate.js +25 -4
  152. package/dist/lib/cms/document-gate.js.map +1 -1
  153. package/dist/lib/cms/published-documents.js +1 -0
  154. package/dist/lib/cms/published-documents.js.map +1 -1
  155. package/dist/lib/cms-views/view-model.d.ts +3 -3
  156. package/dist/lib/data/index.d.ts +0 -3
  157. package/dist/lib/data/index.js +4 -6
  158. package/dist/lib/data/index.js.map +1 -1
  159. package/dist/lib/dnd/drop-rules.d.ts +45 -2
  160. package/dist/lib/dnd/drop-rules.js +64 -9
  161. package/dist/lib/dnd/drop-rules.js.map +1 -1
  162. package/dist/lib/engine-version.d.ts +16 -0
  163. package/dist/lib/engine-version.js +17 -0
  164. package/dist/lib/engine-version.js.map +1 -0
  165. package/dist/lib/i18n/messages.de.js +8 -56
  166. package/dist/lib/i18n/messages.de.js.map +1 -1
  167. package/dist/lib/i18n/messages.en.d.ts +8 -53
  168. package/dist/lib/i18n/messages.en.js +15 -57
  169. package/dist/lib/i18n/messages.en.js.map +1 -1
  170. package/dist/lib/locale/fallback.js +8 -2
  171. package/dist/lib/locale/fallback.js.map +1 -1
  172. package/dist/lib/locale/index.d.ts +0 -1
  173. package/dist/lib/locale/index.js +0 -1
  174. package/dist/lib/locale/index.js.map +1 -1
  175. package/dist/lib/locale/locale-store.d.ts +10 -3
  176. package/dist/lib/locale/locale-store.js +12 -5
  177. package/dist/lib/locale/locale-store.js.map +1 -1
  178. package/dist/lib/operations/session-hydration.d.ts +9 -5
  179. package/dist/lib/operations/session-hydration.js +10 -10
  180. package/dist/lib/operations/session-hydration.js.map +1 -1
  181. package/dist/lib/operations/studio-operations.js +4 -2
  182. package/dist/lib/operations/studio-operations.js.map +1 -1
  183. package/dist/lib/persistence/convex-adapter.js +63 -75
  184. package/dist/lib/persistence/convex-adapter.js.map +1 -1
  185. package/dist/lib/persistence/deployment-readiness.d.ts +8 -1
  186. package/dist/lib/persistence/deployment-readiness.js +4 -0
  187. package/dist/lib/persistence/deployment-readiness.js.map +1 -1
  188. package/dist/lib/persona/labels.d.ts +0 -2
  189. package/dist/lib/persona/labels.js +1 -7
  190. package/dist/lib/persona/labels.js.map +1 -1
  191. package/dist/lib/registry/index.d.ts +4 -2
  192. package/dist/lib/registry/index.js +26 -21
  193. package/dist/lib/registry/index.js.map +1 -1
  194. package/dist/lib/registry/project-components.js +0 -3
  195. package/dist/lib/registry/project-components.js.map +1 -1
  196. package/dist/lib/routes/route-issues.js +4 -5
  197. package/dist/lib/routes/route-issues.js.map +1 -1
  198. package/dist/lib/theme.js +3 -2
  199. package/dist/lib/theme.js.map +1 -1
  200. package/dist/lib/webhooks/tags.js +11 -14
  201. package/dist/lib/webhooks/tags.js.map +1 -1
  202. package/dist/lib/workspace/index.d.ts +1 -1
  203. package/dist/lib/workspace/index.js +1 -1
  204. package/dist/lib/workspace/index.js.map +1 -1
  205. package/dist/previews/enumerate.d.ts +27 -9
  206. package/dist/previews/enumerate.js +27 -6
  207. package/dist/previews/enumerate.js.map +1 -1
  208. package/dist/previews/manifest-format.d.ts +16 -7
  209. package/dist/previews/manifest-format.js +0 -21
  210. package/dist/previews/manifest-format.js.map +1 -1
  211. package/dist/router/match.d.ts +0 -2
  212. package/dist/router/match.js +0 -2
  213. package/dist/router/match.js.map +1 -1
  214. package/dist/ui/badge.d.ts +1 -1
  215. package/package.json +2 -2
  216. package/src/styles/studio.css +5 -4
  217. package/src/styles/tokens.css +72 -55
  218. package/convex/content.ts +0 -291
  219. package/dist/components/collab/collab-context.d.ts +0 -27
  220. package/dist/components/collab/collab-context.js +0 -39
  221. package/dist/components/collab/collab-context.js.map +0 -1
  222. package/dist/components/collab/collab-seed.d.ts +0 -15
  223. package/dist/components/collab/collab-seed.js +0 -20
  224. package/dist/components/collab/collab-seed.js.map +0 -1
  225. package/dist/components/extensions/extensions-view.d.ts +0 -7
  226. package/dist/components/extensions/extensions-view.js +0 -127
  227. package/dist/components/extensions/extensions-view.js.map +0 -1
  228. package/dist/lib/bindings/section-bindings.d.ts +0 -24
  229. package/dist/lib/bindings/section-bindings.js +0 -9
  230. package/dist/lib/bindings/section-bindings.js.map +0 -1
  231. package/dist/lib/data/data-store.d.ts +0 -98
  232. package/dist/lib/data/data-store.js +0 -211
  233. package/dist/lib/data/data-store.js.map +0 -1
  234. package/dist/lib/data/providers.d.ts +0 -143
  235. package/dist/lib/data/providers.js +0 -255
  236. package/dist/lib/data/providers.js.map +0 -1
  237. package/dist/lib/data/sample-capture.d.ts +0 -30
  238. package/dist/lib/data/sample-capture.js +0 -70
  239. package/dist/lib/data/sample-capture.js.map +0 -1
  240. package/dist/lib/data/sources-store.d.ts +0 -42
  241. package/dist/lib/data/sources-store.js +0 -120
  242. package/dist/lib/data/sources-store.js.map +0 -1
  243. package/dist/lib/locale/binding-fallback.d.ts +0 -35
  244. package/dist/lib/locale/binding-fallback.js +0 -73
  245. package/dist/lib/locale/binding-fallback.js.map +0 -1
  246. package/dist/lib/starters/kit-session.d.ts +0 -5
  247. package/dist/lib/starters/kit-session.js +0 -17
  248. package/dist/lib/starters/kit-session.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/ai/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * `@elytracms/studio/lib/ai` — headless AI platform seam types (EC-331, phase 1).\n *\n * Pure types only: this module imports nothing at runtime (every import is\n * `import type`), so referencing `StudioAiConfig` from the studio-config type does\n * NOT pull the `ai` / `@ai-sdk/*` runtime onto the critical path. The runtime lives\n * in the sibling modules (`config`, `anthropic-provider`, `fake-provider`,\n * `knowledge`, `shape`, `apply-content`, `route`, `provenance`), reached only when\n * the `ai` block is configured and the AI subsystem actually boots. The Anthropic\n * provider additionally loads `ai`/`@ai-sdk/anthropic` via dynamic `import()`, so\n * even importing this barrel never eagerly loads the SDK.\n */\nimport type {\n CollectionDef,\n CollectionRegistry,\n CmsValidationIssue,\n FieldValues,\n JsonSchema,\n ValidateDocumentOptions,\n} from '@elytracms/core/cms-core'\nimport type { ComponentManifest } from '@elytracms/core/component-registry'\n// Type-only on purpose (erased at compile; `verbatimModuleSyntax`): referencing the\n// SDK's `LanguageModel` here creates NO runtime edge — pinned in `bundle.test.ts`.\nimport type { LanguageModel } from 'ai'\n\n// --- Provider seam ----------------------------------------------------------------\n\n/**\n * The capabilities the engine requires of a provider. Both must be `true` — the\n * capability gate (`resolveAiConfig`) fails loud otherwise (tool-calling +\n * structured output are the non-negotiable floor for schema-guaranteed authoring).\n */\nexport interface AiProviderCapabilities {\n /** The provider can call tools (function/tool calling). */\n toolCalling: boolean\n /** The provider can return schema-constrained structured output. */\n structuredOutput: boolean\n}\n\n/** A request for one schema-constrained structured object — the engine's core primitive. */\nexport interface GenerateStructuredRequest {\n /** System prompt: rules, injection stance, closed-world constraints. */\n system?: string\n /** The task prompt plus assembled context (knowledge, existing values, prior issues). */\n prompt: string\n /** The target shape as a JSON Schema (draft 2020-12 subset) the output must satisfy. */\n schema: JsonSchema\n /** A short name for the schema (some providers surface it as the tool/output name). */\n schemaName?: string\n /** A one-line description of what the schema represents. */\n schemaDescription?: string\n}\n\n/** Token usage a provider may report (best-effort; recorded for soft spend counters). */\nexport interface AiUsage {\n inputTokens?: number\n outputTokens?: number\n}\n\nexport interface GenerateStructuredResult {\n /** The structured object the provider produced (best-effort match to the request schema). */\n object: unknown\n usage?: AiUsage\n}\n\n/**\n * A provider adapter over a tool-calling, structured-output model. Anthropic (or\n * the Vercel AI Gateway) in production, {@link FakeProvider} (deterministic,\n * keyless) in tests/playground — all implement this identical surface so the whole\n * loop runs without a key.\n */\nexport interface AiProvider {\n /** Stable provider id (e.g. `anthropic`, `fake`); recorded in provenance. */\n readonly id: string\n /** The model id the provider targets, when fixed; recorded in provenance. */\n readonly model?: string\n /** The provider's capabilities — validated by the capability gate at config load. */\n capabilities(): AiProviderCapabilities\n /** Produce a single schema-constrained structured object. */\n generateStructured(request: GenerateStructuredRequest): Promise<GenerateStructuredResult>\n /**\n * The AI-SDK `LanguageModel` behind this provider — the seam the route's native\n * chat branch consumes (EC-334: `streamText` over UIMessages, tools declared\n * without `execute` so they forward to the client). Optional: a pure structured\n * proxy (the client-side route provider) exposes none — the route answers 501\n * for chat requests then.\n */\n languageModel?(): Promise<LanguageModel>\n}\n\n// --- Config seam ------------------------------------------------------------------\n\n/** Soft, advisory limits for the route counter and the engine repair loop. */\nexport interface AiLimits {\n /** Soft per-project ceiling on route requests per minute (advisory; route-enforced). */\n maxRequestsPerMinute?: number\n /** Cap on repair attempts after the first generation (engine default when omitted). */\n maxRepairAttempts?: number\n}\n\n/**\n * The `ai` block of `defineStudio({ ai })` (EC-331). Studio-only live code — like\n * `fieldRenderers` / `i18n`, it never reaches the delivery bundle. The block's\n * ABSENCE means the feature is fully absent (no AI UI, no AI deps on the critical\n * path); `enabled: false` is a temporary kill-switch that keeps the config.\n */\nexport interface StudioAiConfig {\n /**\n * Temporary kill-switch. Presence of the whole `ai` block enables the feature;\n * `enabled: false` disables it without removing the config. Omitted ⇒ enabled.\n */\n enabled?: boolean\n /** The provider adapter (live code): Anthropic in production, FakeProvider in tests/playground. */\n provider: AiProvider\n /** Project knowledge sources assembled into the model's context. */\n knowledge?: KnowledgeSource[]\n /** Soft rate / repair limits. */\n limits?: AiLimits\n}\n\n// --- Knowledge seam ---------------------------------------------------------------\n\n/** An inline knowledge literal (markdown prose versioned with the repo). */\nexport interface KnowledgeItem {\n title?: string\n content: string\n}\n\n/**\n * A `fromCollection('<id>')` source: studio-editable knowledge whose *content* is\n * prose held in the DB (data), while the mechanism stays code. Resolved by a\n * caller-supplied collection reader (starter-kit / studio wires it to operations).\n */\nexport interface KnowledgeCollectionSource {\n readonly kind: 'collection'\n /** Collection id whose documents supply editable knowledge prose. */\n readonly collectionId: string\n /** Field carrying the prose; when omitted the reader picks the collection's title/first text field. */\n readonly field?: string\n}\n\n/** An async (or sync) function producing knowledge items at resolve time. */\nexport type KnowledgeFn = () =>\n | KnowledgeItem\n | KnowledgeItem[]\n | Promise<KnowledgeItem | KnowledgeItem[]>\n\n/** A knowledge source: inline literal, async function, or `fromCollection(...)` sugar. */\nexport type KnowledgeSource = KnowledgeItem | KnowledgeFn | KnowledgeCollectionSource\n\n/** The assembled knowledge context — a flat, deterministic list of resolved items. */\nexport interface ResolvedKnowledge {\n items: KnowledgeItem[]\n}\n\n/** Reads knowledge prose out of a `fromCollection` source (wired to the operations layer). */\nexport type KnowledgeCollectionReader = (\n source: KnowledgeCollectionSource,\n) => KnowledgeItem[] | Promise<KnowledgeItem[]>\n\n// --- Engine seam ------------------------------------------------------------------\n\n/**\n * A relation candidate id (from a `searchDocuments`/tool result). Relation fields may\n * ONLY use ids present here — the target shape emits them as an enum, so a\n * hallucinated id is not even representable as valid structured output.\n */\nexport interface RelationCandidate {\n id: string\n /** Human label (title) for the model to choose against. */\n label?: string\n}\n\n/** Relation candidate ids keyed by field name. A field absent here is omitted from the shape. */\nexport type RelationCandidates = Record<string, RelationCandidate[]>\n\n/**\n * An asset candidate id (from a `listAssets` tool result). Asset/image fields may\n * ONLY use ids present here — the target shape emits them as an enum, so a\n * hallucinated (or invented / \"to-be-uploaded\") asset id is not even representable\n * as valid structured output. From the EXISTING media library ONLY (EC-381): the\n * assistant never generates or uploads an asset; empty beats wrong.\n */\nexport interface AssetCandidate {\n id: string\n /** Human label (title / filename) for the model to choose against. */\n label?: string\n}\n\n/** Asset candidate ids keyed by field name. A field absent here is omitted from the shape. */\nexport type AssetCandidates = Record<string, AssetCandidate[]>\n\n/** The typed draft-values patch the engine emits — applied by the draft-write path. */\nexport interface ContentPatch {\n collection: string\n id: string\n /** Non-localized field values. */\n values: FieldValues\n /** Per-locale field values (localized fields, under the target locale). */\n localized?: Record<string, FieldValues>\n}\n\n/** Origin marker the draft-write path records so an AI-authored draft is attributable. */\nexport interface AiProvenance {\n origin: 'assistant'\n /** Provider id (e.g. `anthropic`, `fake`). */\n provider: string\n /** Model id, when the provider fixes one. */\n model?: string\n /** ISO timestamp when the content was generated. */\n at: string\n}\n\nexport interface ApplyContentInput {\n provider: AiProvider\n registry: CollectionRegistry\n collection: CollectionDef\n /** Document id the patch targets (an existing doc for updates, or a fresh id for creation). */\n documentId: string\n /** The author's instruction / prompt. */\n instruction: string\n /** Assembled knowledge context (from `resolveKnowledge`). */\n knowledge?: ResolvedKnowledge\n /** Component manifests — context for `allow`-leashed richText/blocks fields. */\n components?: readonly ComponentManifest[]\n /** Relation candidate ids by field — the ONLY ids a relation field may use. */\n candidates?: RelationCandidates\n /**\n * Asset candidate ids by field — the ONLY ids an asset/image field may use\n * (EC-381). Emitted as an enum; an asset field with none is omitted from the\n * shape (so a create proposal simply leaves it empty — empty beats wrong).\n */\n assetCandidates?: AssetCandidates\n /** Existing draft values (updates): the model output merges over these before validation. */\n existing?: FieldValues\n /** Target locale for localized fields (their values land under `localized[locale]`). */\n locale?: string\n /**\n * THE validation option bag (EC-497) — the studio session's\n * `gateValidateOptions(...)`, passed WHOLE rather than reassembled from\n * individual keys here. EC-473 had already established that the assistant must\n * judge its output by the editor's rules; this makes that structural: there is\n * one bag, and a surface cannot quietly take a subset of it. `localeConfig` is\n * overridden per generation (a create targets ONE locale), which is the single\n * documented deviation and is written at the override, not implied by an\n * omission.\n */\n validateOptions?: ValidateDocumentOptions\n /** Max repair attempts after the first generation (default {@link DEFAULT_MAX_REPAIR_ATTEMPTS}). */\n maxRepairAttempts?: number\n}\n\n/** The engine's outcome: a valid, leash-compliant patch, or the blocking issues. */\nexport type ApplyContentResult =\n | {\n ok: true\n patch: ContentPatch\n provenance: AiProvenance\n /** Total generation attempts made (1 = happy path, >1 = repaired). */\n attempts: number\n /** Non-error issues surfaced by the accepted document (e.g. warnings). */\n issues: CmsValidationIssue[]\n }\n | {\n ok: false\n /** The error-severity issues from the final failed attempt. */\n issues: CmsValidationIssue[]\n attempts: number\n provenance: AiProvenance\n }\n\n// --- Route seam -------------------------------------------------------------------\n\n/** A validated studio session, from the host-wired `getSession`. Opaque beyond `userId`. */\nexport interface AiSession {\n /** Authenticated principal id. */\n userId: string\n [key: string]: unknown\n}\n\nexport interface AiRouteHandlerOptions {\n /** The provider (holds the host-env key). The route is a thin proxy over it. */\n provider: AiProvider\n /**\n * Server-side session check (reject anonymous callers). Returns a session for an\n * authenticated caller, `null` otherwise. Wired by the host to its own auth — the\n * route consumes it, never re-implements it.\n */\n getSession: (request: Request) => AiSession | null | Promise<AiSession | null>\n /** Soft per-project rate limit (advisory spend guard). */\n limits?: AiLimits\n /** Derive the per-project rate-bucket key from a request (default: one global bucket). */\n projectKey?: (request: Request) => string\n}\n\n/** The mounted route handler: a framework-agnostic Web `Request → Response`. */\nexport type AiRouteHandler = (request: Request) => Promise<Response>\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/ai/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * `@elytracms/studio/lib/ai` — headless AI platform seam types (EC-331, phase 1).\n *\n * Pure types only: this module imports nothing at runtime (every import is\n * `import type`), so referencing `StudioAiConfig` from the studio-config type does\n * NOT pull the `ai` / `@ai-sdk/*` runtime onto the critical path. The runtime lives\n * in the sibling modules (`config`, `anthropic-provider`, `fake-provider`,\n * `knowledge`, `shape`, `apply-content`, `route`, `provenance`), reached only when\n * the `ai` block is configured and the AI subsystem actually boots. The Anthropic\n * provider additionally loads `ai`/`@ai-sdk/anthropic` via dynamic `import()`, so\n * even importing this barrel never eagerly loads the SDK.\n */\nimport type {\n CollectionDef,\n CollectionRegistry,\n CmsValidationIssue,\n FieldValues,\n JsonSchema,\n ValidateDocumentOptions,\n} from '@elytracms/core/cms-core'\nimport type { ComponentManifest } from '@elytracms/core/component-registry'\n// Type-only on purpose (erased at compile; `verbatimModuleSyntax`): referencing the\n// SDK's `LanguageModel` here creates NO runtime edge — pinned in `bundle.test.ts`.\nimport type { LanguageModel } from 'ai'\n\n// --- Provider seam ----------------------------------------------------------------\n\n/**\n * The capabilities the engine requires of a provider. Both must be `true` — the\n * capability gate (`resolveAiConfig`) fails loud otherwise (tool-calling +\n * structured output are the non-negotiable floor for schema-guaranteed authoring).\n */\nexport interface AiProviderCapabilities {\n /** The provider can call tools (function/tool calling). */\n toolCalling: boolean\n /** The provider can return schema-constrained structured output. */\n structuredOutput: boolean\n}\n\n/** A request for one schema-constrained structured object — the engine's core primitive. */\nexport interface GenerateStructuredRequest {\n /** System prompt: rules, injection stance, closed-world constraints. */\n system?: string\n /** The task prompt plus assembled context (knowledge, existing values, prior issues). */\n prompt: string\n /** The target shape as a JSON Schema (draft 2020-12 subset) the output must satisfy. */\n schema: JsonSchema\n /** A short name for the schema (some providers surface it as the tool/output name). */\n schemaName?: string\n /** A one-line description of what the schema represents. */\n schemaDescription?: string\n}\n\n/** Token usage a provider may report (best-effort; recorded for soft spend counters). */\nexport interface AiUsage {\n inputTokens?: number\n outputTokens?: number\n}\n\nexport interface GenerateStructuredResult {\n /** The structured object the provider produced (best-effort match to the request schema). */\n object: unknown\n usage?: AiUsage\n}\n\n/**\n * A provider adapter over a tool-calling, structured-output model. Anthropic (or\n * the Vercel AI Gateway) in production, {@link FakeProvider} (deterministic,\n * keyless) in tests/playground — all implement this identical surface so the whole\n * loop runs without a key.\n */\nexport interface AiProvider {\n /** Stable provider id (e.g. `anthropic`, `fake`); recorded in provenance. */\n readonly id: string\n /** The model id the provider targets, when fixed; recorded in provenance. */\n readonly model?: string\n /** The provider's capabilities — validated by the capability gate at config load. */\n capabilities(): AiProviderCapabilities\n /** Produce a single schema-constrained structured object. */\n generateStructured(request: GenerateStructuredRequest): Promise<GenerateStructuredResult>\n /**\n * The AI-SDK `LanguageModel` behind this provider — the seam the route's native\n * chat branch consumes (EC-334: `streamText` over UIMessages, tools declared\n * without `execute` so they forward to the client). Optional: a pure structured\n * proxy (the client-side route provider) exposes none — the route answers 501\n * for chat requests then.\n */\n languageModel?(): Promise<LanguageModel>\n}\n\n// --- Config seam ------------------------------------------------------------------\n\n/** Soft, advisory limits for the route counter and the engine repair loop. */\nexport interface AiLimits {\n /** Soft per-project ceiling on route requests per minute (advisory; route-enforced). */\n maxRequestsPerMinute?: number\n /** Cap on repair attempts after the first generation (engine default when omitted). */\n maxRepairAttempts?: number\n}\n\n/**\n * The `ai` block of `defineStudio({ ai })` (EC-331). Studio-only live code — like\n * `fieldRenderers` / `i18n`, it never reaches the delivery bundle. The block's\n * ABSENCE means the feature is fully absent (no AI UI, no AI deps on the critical\n * path); `enabled: false` is a temporary kill-switch that keeps the config.\n */\nexport interface StudioAiConfig {\n /**\n * Temporary kill-switch. Presence of the whole `ai` block enables the feature;\n * `enabled: false` disables it without removing the config. Omitted ⇒ enabled.\n */\n enabled?: boolean\n /** The provider adapter (live code): Anthropic in production, FakeProvider in tests/playground. */\n provider: AiProvider\n /** Project knowledge sources assembled into the model's context. */\n knowledge?: KnowledgeSource[]\n /** Soft rate / repair limits. */\n limits?: AiLimits\n}\n\n// --- Knowledge seam ---------------------------------------------------------------\n\n/** An inline knowledge literal (markdown prose versioned with the repo). */\nexport interface KnowledgeItem {\n title?: string\n content: string\n}\n\n/**\n * A `fromCollection('<id>')` source: studio-editable knowledge whose *content* is\n * prose held in the DB (data), while the mechanism stays code. Resolved by a\n * caller-supplied collection reader (starter-kit / studio wires it to operations).\n */\nexport interface KnowledgeCollectionSource {\n readonly kind: 'collection'\n /** Collection id whose documents supply editable knowledge prose. */\n readonly collectionId: string\n /** Field carrying the prose; when omitted the reader picks the collection's title/first text field. */\n readonly field?: string\n}\n\n/** An async (or sync) function producing knowledge items at resolve time. */\nexport type KnowledgeFn = () =>\n | KnowledgeItem\n | KnowledgeItem[]\n | Promise<KnowledgeItem | KnowledgeItem[]>\n\n/** A knowledge source: inline literal, async function, or `fromCollection(...)` sugar. */\nexport type KnowledgeSource = KnowledgeItem | KnowledgeFn | KnowledgeCollectionSource\n\n/** The assembled knowledge context — a flat, deterministic list of resolved items. */\nexport interface ResolvedKnowledge {\n items: KnowledgeItem[]\n}\n\n/** Reads knowledge prose out of a `fromCollection` source (wired to the operations layer). */\nexport type KnowledgeCollectionReader = (\n source: KnowledgeCollectionSource,\n) => KnowledgeItem[] | Promise<KnowledgeItem[]>\n\n// --- Engine seam ------------------------------------------------------------------\n\n/**\n * A relation candidate id (from a `searchDocuments`/tool result). Relation fields may\n * ONLY use ids present here — the target shape emits them as an enum, so a\n * hallucinated id is not even representable as valid structured output.\n */\nexport interface RelationCandidate {\n id: string\n /** Human label (title) for the model to choose against. */\n label?: string\n}\n\n/** Relation candidate ids keyed by field name. A field absent here is omitted from the shape. */\nexport type RelationCandidates = Record<string, RelationCandidate[]>\n\n/**\n * An asset candidate id (from a `listAssets` tool result). Asset/image fields may\n * ONLY use ids present here — the target shape emits them as an enum, so a\n * hallucinated (or invented / \"to-be-uploaded\") asset id is not even representable\n * as valid structured output. From the EXISTING media library ONLY (EC-381): the\n * assistant never generates or uploads an asset; empty beats wrong.\n */\nexport interface AssetCandidate {\n id: string\n /** Human label (title / filename) for the model to choose against. */\n label?: string\n}\n\n/** Asset candidate ids keyed by field name. A field absent here is omitted from the shape. */\nexport type AssetCandidates = Record<string, AssetCandidate[]>\n\n/** The typed draft-values patch the engine emits — applied by the draft-write path. */\nexport interface ContentPatch {\n collection: string\n id: string\n /** Non-localized field values. */\n values: FieldValues\n /** Per-locale field values (localized fields, under the target locale). */\n localized?: Record<string, FieldValues>\n}\n\n/** Origin marker the draft-write path records so an AI-authored draft is attributable. */\nexport interface AiProvenance {\n origin: 'assistant'\n /** Provider id (e.g. `anthropic`, `fake`). */\n provider: string\n /** Model id, when the provider fixes one. */\n model?: string\n /** ISO timestamp when the content was generated. */\n at: string\n}\n\nexport interface ApplyContentInput {\n provider: AiProvider\n registry: CollectionRegistry\n collection: CollectionDef\n /** Document id the patch targets (an existing doc for updates, or a fresh id for creation). */\n documentId: string\n /** The author's instruction / prompt. */\n instruction: string\n /** Assembled knowledge context (from `resolveKnowledge`). */\n knowledge?: ResolvedKnowledge\n /** Component manifests — context for `allow`-leashed richText/blocks fields. */\n components?: readonly ComponentManifest[]\n /** Relation candidate ids by field — the ONLY ids a relation field may use. */\n candidates?: RelationCandidates\n /**\n * Asset candidate ids by field — the ONLY ids an asset/image field may use\n * (EC-381). Emitted as an enum; an asset field with none is omitted from the\n * shape (so a create proposal simply leaves it empty — empty beats wrong).\n */\n assetCandidates?: AssetCandidates\n /** Existing draft values (updates): the model output merges over these before validation. */\n existing?: FieldValues\n /** Target locale for localized fields (their values land under `localized[locale]`). */\n locale?: string\n /**\n * THE validation option bag (EC-497) — the studio session's\n * `gateValidateOptions(...)`, passed WHOLE rather than reassembled from\n * individual keys here. EC-473 had already established that the assistant must\n * judge its output by the editor's rules; this makes that structural: there is\n * one bag, and a surface cannot quietly take a subset of it. `localeConfig` is\n * overridden per generation (a create targets ONE locale), which is the single\n * documented deviation and is written at the override, not implied by an\n * omission.\n */\n validateOptions?: ValidateDocumentOptions\n /** Max repair attempts after the first generation (default {@link DEFAULT_MAX_REPAIR_ATTEMPTS}). */\n maxRepairAttempts?: number\n}\n\n/** The engine's outcome: a valid, leash-compliant patch, or the blocking issues. */\nexport type ApplyContentResult =\n | {\n ok: true\n patch: ContentPatch\n provenance: AiProvenance\n /** Total generation attempts made (1 = happy path, >1 = repaired). */\n attempts: number\n /** Non-error issues surfaced by the accepted document (e.g. warnings). */\n issues: CmsValidationIssue[]\n }\n | {\n ok: false\n /** The error-severity issues from the final failed attempt. */\n issues: CmsValidationIssue[]\n attempts: number\n provenance: AiProvenance\n }\n\n// --- Route seam -------------------------------------------------------------------\n\n/** A validated studio session, from the host-wired `getSession`. Opaque beyond `userId`. */\nexport interface AiSession {\n /** Authenticated principal id. */\n userId: string\n [key: string]: unknown\n}\n\nexport interface AiRouteHandlerOptions {\n /** The provider (holds the host-env key). The route is a thin proxy over it. */\n provider: AiProvider\n /**\n * Server-side session check (reject anonymous callers). Returns a session for an\n * authenticated caller, `null` otherwise. Wired by the host to its own auth — the\n * route consumes it, never re-implements it.\n */\n getSession: (request: Request) => AiSession | null | Promise<AiSession | null>\n /** Soft per-project rate limit (advisory spend guard). */\n limits?: AiLimits\n /** Derive the per-project rate-bucket key from a request (default: one global bucket). */\n projectKey?: (request: Request) => string\n /**\n * Millisecond clock the rate window is decided against (default `Date.now`).\n * Injected so the 60 s boundary is testable with a fixed clock (EC-602, the\n * AGENTS.md §4 determinism rule). Milliseconds rather than the house ISO\n * `Clock` (`@elytracms/core/determinism`): that one stamps records; this one\n * does window arithmetic.\n */\n now?: () => number\n}\n\n/** The mounted route handler: a framework-agnostic Web `Request → Response`. */\nexport type AiRouteHandler = (request: Request) => Promise<Response>\n"]}
@@ -34,9 +34,10 @@
34
34
  * it to `getDocument` + the candidate store and hands the result to the review
35
35
  * sink.
36
36
  */
37
- import { assetNode, cmsIssue, isFieldLocalized, readAssetId, readDocumentRef, referenceNode, validateDocument, } from '@elytracms/core/cms-core';
38
- import { blockRootsOf, staticProp } from '@elytracms/core/project-graph';
37
+ import { cmsIssue, isFieldLocalized, readAssetId, readDocumentRef, referenceNode, validateDocument, } from '@elytracms/core/cms-core';
38
+ import { blockRootsOf, editBlockRoots, staticProp } from '@elytracms/core/project-graph';
39
39
  import { diffDocuments } from '@elytracms/core/content';
40
+ import { carryAssetPlacements } from '../assets/asset-placements.js';
40
41
  import { introducedErrors, warningsOf } from './proposal-validation.js';
41
42
  import { richTextValueFromModelInput } from './rich-text-input.js';
42
43
  function isNonEmptyString(value) {
@@ -65,6 +66,15 @@ function writeFieldValue(doc, fieldName, locale, value) {
65
66
  values[fieldName] = value;
66
67
  return { ...doc, values };
67
68
  }
69
+ /**
70
+ * The read twin of {@link writeFieldValue}: the field's value in the resolved
71
+ * `locale` bucket, or in the shared `values` for a non-localized field. The exact
72
+ * bucket only, with no default-locale fallback, because that bucket is the one the
73
+ * write replaces.
74
+ */
75
+ function readFieldValue(doc, fieldName, locale) {
76
+ return locale !== undefined ? doc.localized?.[locale]?.[fieldName] : doc.values[fieldName];
77
+ }
68
78
  /** Relation ids CURRENTLY on the document for a field (any bucket) — re-usable without a search. */
69
79
  function currentRelationIds(doc, fieldName) {
70
80
  const ids = new Set();
@@ -95,8 +105,13 @@ function currentAssetIds(doc, fieldName) {
95
105
  collect(bucket[fieldName]);
96
106
  return ids;
97
107
  }
98
- /** Map a change's raw value into the stored value shape (envelopes; loud leash). */
99
- function mapUpdateValue(field, change, document, input, issue) {
108
+ /**
109
+ * Map a change's raw value into the stored value shape (envelopes; loud leash).
110
+ * `document` is the ORIGINAL document, which is what the id leash reads. `current`
111
+ * is the value this change replaces, taken from the resolved locale bucket of the
112
+ * working copy. The asset sub-field carry reads it (EC-558).
113
+ */
114
+ function mapUpdateValue(field, change, document, current, input, issue) {
100
115
  const raw = change.value;
101
116
  if (raw === undefined || raw === null)
102
117
  return { value: undefined }; // clear
@@ -141,8 +156,13 @@ function mapUpdateValue(field, change, document, input, issue) {
141
156
  if (!field.multiple && ids.length > 1) {
142
157
  return issue('invalid-field-value', `Field "${field.name}" holds a single asset — pass one id.`);
143
158
  }
144
- const nodes = ids.map((id) => assetNode(id));
145
- return { value: field.multiple ? nodes : nodes[0] };
159
+ // EC-558: replace-with-list through the one carry rule. A held id keeps its
160
+ // placement's per-use sub-fields (a caption, say), a single swap carries
161
+ // them to the new image, and a NEW id is an envelope (EC-381). Data about
162
+ // the image itself (alt, an AI flag) belongs on the asset's `meta`.
163
+ return {
164
+ value: carryAssetPlacements(current, field.multiple ? { multiple: true, ids } : { multiple: false, id: ids[0] ?? null }, 'envelope'),
165
+ };
146
166
  }
147
167
  case 'richText': {
148
168
  // EC-379: a string value is MARKDOWN, converted through the engine's strict
@@ -172,8 +192,7 @@ function applyBlockPropChange(doc, field, change, locale, issue) {
172
192
  if (!isNonEmptyString(change.prop)) {
173
193
  return issue('invalid-field-value', `Changing block "${change.blockId}" needs "prop" — the component property to change.`);
174
194
  }
175
- const bucket = locale !== undefined ? doc.localized?.[locale] : doc.values;
176
- const original = bucket?.[change.field];
195
+ const original = readFieldValue(doc, change.field, locale);
177
196
  const blocks = blockRootsOf(original);
178
197
  const index = blocks.findIndex((block) => block.id === change.blockId);
179
198
  if (index < 0) {
@@ -186,9 +205,10 @@ function applyBlockPropChange(doc, field, change, locale, issue) {
186
205
  else
187
206
  props[change.prop] = staticProp(change.value);
188
207
  const nextBlock = { ...block, props };
189
- const nextBlocks = blocks.map((b, i) => (i === index ? nextBlock : b));
190
- // Preserve the stored shape: an array for a `multiple` composition, a bare node otherwise.
191
- const value = Array.isArray(original) ? nextBlocks : nextBlocks[0];
208
+ // EC-576: through the core write path — the other roots and every typography
209
+ // item keep their place, and the write is the v2 sequence. (`blocks` is
210
+ // `editBlockRoots`' own root list, so `index` addresses the same root.)
211
+ const value = editBlockRoots(original, (roots) => roots.map((b, i) => (i === index ? nextBlock : b)));
192
212
  return { doc: writeFieldValue(doc, change.field, locale, value) };
193
213
  }
194
214
  /** Apply ONE change to a (copy of the) document, or report the targeting issue. */
@@ -227,7 +247,8 @@ function applyOneChange(input, doc, change) {
227
247
  if (change.blockId !== undefined || change.prop !== undefined) {
228
248
  return applyBlockPropChange(doc, field, change, locale, issue);
229
249
  }
230
- const mapped = mapUpdateValue(field, change, input.document, input, issue);
250
+ const current = readFieldValue(doc, change.field, locale);
251
+ const mapped = mapUpdateValue(field, change, input.document, current, input, issue);
231
252
  if ('issue' in mapped)
232
253
  return mapped;
233
254
  return { doc: writeFieldValue(doc, change.field, locale, mapped.value) };
@@ -1 +1 @@
1
- {"version":3,"file":"update-fields.js","sourceRoot":"","sources":["../../../src/lib/ai/update-fields.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,OAAO,EACL,SAAS,EACT,QAAQ,EACR,gBAAgB,EAChB,WAAW,EACX,eAAe,EACf,aAAa,EACb,gBAAgB,GACjB,MAAM,0BAA0B,CAAA;AAUjC,OAAO,EAAE,YAAY,EAAE,UAAU,E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CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE;gBAC/B,CAAC,CAAC,EAAE,CAAC;SACR;QACD,MAAM,EAAE;YACN,MAAM,EAAE,QAAQ,CAAC,MAAM;YACvB,GAAG,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACjE;QACD,aAAa,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CACzC,MAAM,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,KAAK,KAAK,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAClF;QACD,MAAM,EAAE,UAAU,CAAC,MAAM,CAAC;KAC3B,CAAA;AACH,CAAC","sourcesContent":["/**\n * `buildUpdateProposal` — the EC-378 update-proposal builder (the edit-flow\n * counterpart of `applyContentWithShape`, minus the generation step).\n *\n * The MODEL authors the field changes directly in the `updateFields` tool input\n * (it has the conversation + `getDocument` output as context); this module turns\n * those changes into a reviewable proposal with the SAME engine discipline the\n * create flow has:\n *\n * - **merge semantics**: changes apply per field over the EXISTING document —\n * never a whole-document rewrite; the patch is the merged document, the diff\n * (`diffDocuments`) is what the editor reviews (changed fields only).\n * - **targeting is addressed with the engine's existing conventions** — field\n * name + optional locale bucket (the diff / `RestoreScope` shape) and, inside\n * a `blocks` field, `blockId` + `prop` (the `BlockChange`/`PropChange` shape,\n * root blocks by stable node id). No new path grammar.\n * - **leashes hold, loudly**: `ai.exclude` fields are untouchable; relation AND\n * asset ids (EC-381) must come from searched candidates (`searchDocuments` /\n * `listAssets`) or already be on the document; every targeting failure is an\n * explicit issue — never a silent drop (unlike the create shape, which makes bad\n * ids structurally unrepresentable, an update change is imperative — so it FAILS\n * instead of being filtered).\n * - **validation parity**: the merged document runs through `validateDocument`\n * with the studio's injected leashes. Only errors the change INTRODUCES block\n * the proposal — pre-existing brokenness on the document is not the\n * assistant's doing and must not force a whole-document repair (the editor's\n * own save path tolerates it the same way; errors gate publish, not drafts).\n *\n * Locale-awareness: a localized field's change lands in the change's `locale`,\n * defaulting to the editor's working locale (`input.locale`). Non-localized\n * fields reject a `locale` loudly.\n *\n * Pure and deterministic — no provider, no I/O; the executor (`tools.ts`) wires\n * it to `getDocument` + the candidate store and hands the result to the review\n * sink.\n */\nimport {\n assetNode,\n cmsIssue,\n isFieldLocalized,\n readAssetId,\n readDocumentRef,\n referenceNode,\n validateDocument,\n} from '@elytracms/core/cms-core'\nimport type {\n CmsDocument,\n CmsValidationIssue,\n CollectionDef,\n CollectionRegistry,\n FieldDef,\n FieldValues,\n ValidateDocumentOptions,\n} from '@elytracms/core/cms-core'\nimport { blockRootsOf, staticProp } from '@elytracms/core/project-graph'\nimport type { ComponentNode, JsonValue } from '@elytracms/core/project-graph'\nimport { diffDocuments } from '@elytracms/core/content'\nimport { introducedErrors, warningsOf } from './proposal-validation'\nimport { richTextValueFromModelInput } from './rich-text-input'\nimport type { AssetCandidates, ContentPatch, RelationCandidates } from './types'\n\n/**\n * One field change of an `updateFields` proposal, addressed with the engine's\n * existing conventions (diff / restore-scope): `field` (+ `locale` bucket for a\n * localized field), and for a `blocks` field optionally `blockId` + `prop` to\n * change one component prop of one root block. `value` is the new value\n * (`null`/omitted clears the field or prop).\n */\nexport interface UpdateFieldChange {\n field: string\n /** Locale bucket for a LOCALIZED field (defaults to the editor's working locale). */\n locale?: string\n /** For a `blocks` field: the root block's stable node id (from `getDocument`). */\n blockId?: string\n /** With `blockId`: the component prop to change. */\n prop?: string\n /** The new value; `null` / omitted clears the field or prop. */\n value?: unknown\n}\n\nexport interface BuildUpdateProposalInput {\n registry: CollectionRegistry\n collection: CollectionDef\n /** The CURRENT document — the proposal's \"before\" side. Never mutated. */\n document: CmsDocument\n changes: readonly UpdateFieldChange[]\n /** The editor's working locale — the default bucket for localized fields. */\n locale?: string\n /** Relation candidates (searched ids) keyed by field name — the id leash. */\n candidates?: RelationCandidates\n /** Asset candidates (searched library ids) keyed by field name — the asset id leash (EC-381). */\n assetCandidates?: AssetCandidates\n /**\n * THE validation option bag (EC-497) — the studio session's\n * `gateValidateOptions(...)`, whole. It also carries the project's\n * `localeConfig`, which is what the unknown-locale targeting check reads: one\n * source for \"which locales exist\", not two that can disagree.\n */\n validateOptions?: ValidateDocumentOptions\n}\n\n/** The `before` snapshot the review diff renders against. */\nexport interface UpdateBeforeSnapshot {\n values: FieldValues\n localized?: Record<string, FieldValues>\n}\n\nexport type BuildUpdateProposalResult =\n | {\n ok: true\n kind: 'proposal'\n /** The MERGED document as a patch (full values; the diff shows changed fields only). */\n patch: ContentPatch\n before: UpdateBeforeSnapshot\n /** Human-readable descriptors of the changed fields (e.g. `title (de)`). */\n changedFields: string[]\n /** Non-error issues on the accepted result (warnings). */\n issues: CmsValidationIssue[]\n }\n | {\n /** Every change resolved to the current values — nothing to propose. */\n ok: true\n kind: 'no-change'\n }\n | { ok: false; issues: CmsValidationIssue[] }\n\ntype ChangeIssue = { issue: CmsValidationIssue }\ntype ChangeOutcome = { doc: CmsDocument } | ChangeIssue\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0\n}\n\n/**\n * The present/absent-key field write — the same semantics as the editor's\n * single-sourced `setFieldValue` (`lib/locale/fallback`): a resolved `locale`\n * writes the `localized[locale]` bucket, clearing DELETES the key. Local here\n * (not imported) because this module takes the locale as an already-resolved\n * argument per change; the semantics are pinned by tests on both sides.\n */\nfunction writeFieldValue(\n doc: CmsDocument,\n fieldName: string,\n locale: string | undefined,\n value: unknown,\n): CmsDocument {\n if (locale !== undefined) {\n const perLocale = { ...(doc.localized?.[locale] ?? {}) }\n if (value === undefined) delete perLocale[fieldName]\n else perLocale[fieldName] = value\n return { ...doc, localized: { ...doc.localized, [locale]: perLocale } }\n }\n const values = { ...doc.values }\n if (value === undefined) delete values[fieldName]\n else values[fieldName] = value\n return { ...doc, values }\n}\n\n/** Relation ids CURRENTLY on the document for a field (any bucket) — re-usable without a search. */\nfunction currentRelationIds(doc: CmsDocument, fieldName: string): Set<string> {\n const ids = new Set<string>()\n const collect = (value: unknown) => {\n for (const entry of Array.isArray(value) ? value : [value]) {\n const ref = readDocumentRef(entry)\n if (ref) ids.add(ref.id)\n }\n }\n collect(doc.values[fieldName])\n for (const bucket of Object.values(doc.localized ?? {})) collect(bucket[fieldName])\n return ids\n}\n\n/** Asset ids CURRENTLY on the document for a field (any bucket) — re-usable without a search (EC-381). */\nfunction currentAssetIds(doc: CmsDocument, fieldName: string): Set<string> {\n const ids = new Set<string>()\n const collect = (value: unknown) => {\n for (const entry of Array.isArray(value) ? value : [value]) {\n const id = readAssetId(entry)\n if (id) ids.add(id)\n }\n }\n collect(doc.values[fieldName])\n for (const bucket of Object.values(doc.localized ?? {})) collect(bucket[fieldName])\n return ids\n}\n\n/** Map a change's raw value into the stored value shape (envelopes; loud leash). */\nfunction mapUpdateValue(\n field: FieldDef,\n change: UpdateFieldChange,\n document: CmsDocument,\n input: BuildUpdateProposalInput,\n issue: (code: Parameters<typeof cmsIssue>[0]['code'], message: string) => ChangeIssue,\n): { value: unknown } | ChangeIssue {\n const raw = change.value\n if (raw === undefined || raw === null) return { value: undefined } // clear\n switch (field.type) {\n case 'relation': {\n const ids = Array.isArray(raw) ? raw : [raw]\n if (!ids.every(isNonEmptyString)) {\n return issue(\n 'invalid-field-value',\n `Relation \"${field.name}\" takes document id string(s) from searchDocuments results.`,\n )\n }\n // The id leash (same stance as the create enum, but LOUD): only searched\n // candidate ids or ids already on the document are usable.\n const allowed = new Set([\n ...(input.candidates?.[field.name] ?? []).map((c) => c.id),\n ...currentRelationIds(document, field.name),\n ])\n const unknown = ids.filter((id) => !allowed.has(id))\n if (unknown.length > 0) {\n return issue(\n 'unknown-relation-target',\n `Relation \"${field.name}\" may only use ids from searchDocuments results — search \"${field.target}\" first (got: ${unknown.join(', ')}).`,\n )\n }\n if (!field.multiple && ids.length > 1) {\n return issue('invalid-field-value', `Field \"${field.name}\" holds a single reference — pass one id.`)\n }\n const refs = ids.map((id) => referenceNode({ collection: field.target, id }))\n return { value: field.multiple ? refs : refs[0] }\n }\n case 'asset': {\n const ids = Array.isArray(raw) ? raw : [raw]\n if (!ids.every(isNonEmptyString)) {\n return issue(\n 'invalid-field-value',\n `Asset field \"${field.name}\" takes asset id string(s) from listAssets results.`,\n )\n }\n // EC-381 — the asset id leash (same stance as relations, but LOUD): only\n // searched library candidate ids or ids already on the document are usable;\n // the assistant never invents or uploads an asset.\n const allowed = new Set([\n ...(input.assetCandidates?.[field.name] ?? []).map((c) => c.id),\n ...currentAssetIds(document, field.name),\n ])\n const unknown = ids.filter((id) => !allowed.has(id))\n if (unknown.length > 0) {\n return issue(\n 'unknown-asset',\n `Asset field \"${field.name}\" may only use ids from listAssets results — search the media library first (got: ${unknown.join(', ')}).`,\n )\n }\n if (!field.multiple && ids.length > 1) {\n return issue('invalid-field-value', `Field \"${field.name}\" holds a single asset — pass one id.`)\n }\n const nodes = ids.map((id) => assetNode(id))\n return { value: field.multiple ? nodes : nodes[0] }\n }\n case 'richText': {\n // EC-379: a string value is MARKDOWN, converted through the engine's strict\n // subset converter; out-of-subset constructs fail LOUD (the model retries\n // in-conversation). A `{ version, doc }` envelope object stays accepted for\n // robustness (getDocument may have shown one) — see rich-text-input.ts.\n const converted = richTextValueFromModelInput(raw)\n if (!converted.ok) {\n return issue('invalid-field-value', `Field \"${field.name}\": ${converted.problems.join(' ')}`)\n }\n return { value: converted.value }\n }\n default:\n // text / number / boolean / date / select / object / blocks: as-is\n // (the merged document's validateDocument run is the shape leash).\n return { value: raw }\n }\n}\n\n/** Change one component prop of one root block (the `BlockChange`/`PropChange` address). */\nfunction applyBlockPropChange(\n doc: CmsDocument,\n field: FieldDef,\n change: UpdateFieldChange,\n locale: string | undefined,\n issue: (code: Parameters<typeof cmsIssue>[0]['code'], message: string) => ChangeIssue,\n): ChangeOutcome {\n if (field.type !== 'blocks') {\n return issue(\n 'invalid-field-value',\n `\"${change.field}\" is not a blocks field — omit \"blockId\"/\"prop\" (set the field value directly).`,\n )\n }\n if (!isNonEmptyString(change.blockId)) {\n return issue(\n 'invalid-field-value',\n `Changing a block on \"${change.field}\" needs \"blockId\" — block ids come from getDocument.`,\n )\n }\n if (!isNonEmptyString(change.prop)) {\n return issue(\n 'invalid-field-value',\n `Changing block \"${change.blockId}\" needs \"prop\" — the component property to change.`,\n )\n }\n const bucket = locale !== undefined ? doc.localized?.[locale] : doc.values\n const original = bucket?.[change.field]\n const blocks = blockRootsOf(original)\n const index = blocks.findIndex((block) => block.id === change.blockId)\n if (index < 0) {\n return issue(\n 'invalid-field-value',\n `Block \"${change.blockId}\" was not found on \"${change.field}\" — read the document first; block ids come from getDocument.`,\n )\n }\n const block = blocks[index]!\n const props = { ...(block.props ?? {}) }\n if (change.value === undefined || change.value === null) delete props[change.prop]\n else props[change.prop] = staticProp(change.value as JsonValue)\n const nextBlock: ComponentNode = { ...block, props }\n const nextBlocks = blocks.map((b, i) => (i === index ? nextBlock : b))\n // Preserve the stored shape: an array for a `multiple` composition, a bare node otherwise.\n const value = Array.isArray(original) ? nextBlocks : nextBlocks[0]\n return { doc: writeFieldValue(doc, change.field, locale, value) }\n}\n\n/** Apply ONE change to a (copy of the) document, or report the targeting issue. */\nfunction applyOneChange(\n input: BuildUpdateProposalInput,\n doc: CmsDocument,\n change: UpdateFieldChange,\n): ChangeOutcome {\n const { collection } = input\n const issue = (\n code: Parameters<typeof cmsIssue>[0]['code'],\n message: string,\n ): ChangeIssue => ({\n issue: cmsIssue({\n code,\n message,\n path: ['documents', `${collection.id}:${doc.id}`, 'values', change.field],\n collectionId: collection.id,\n documentId: doc.id,\n meta: { field: change.field, ...(change.locale !== undefined ? { locale: change.locale } : {}) },\n }),\n })\n\n const field = collection.fields.find((f) => f.name === change.field)\n if (!field) {\n return issue(\n 'invalid-field-value',\n `Unknown field \"${change.field}\" on collection \"${collection.id}\" — use a field name from the schema.`,\n )\n }\n if (field.ai?.exclude) {\n return issue('invalid-field-value', `Field \"${change.field}\" must not be edited by the assistant.`)\n }\n\n const localized = isFieldLocalized(collection, change.field)\n if (!localized && change.locale !== undefined) {\n return issue('unknown-locale', `Field \"${change.field}\" is not localized — omit \"locale\".`)\n }\n if (\n change.locale !== undefined &&\n input.validateOptions?.localeConfig &&\n !input.validateOptions.localeConfig.locales.includes(change.locale)\n ) {\n return issue(\n 'unknown-locale',\n `Unknown locale \"${change.locale}\" — this project has: ${input.validateOptions?.localeConfig?.locales.join(', ')}.`,\n )\n }\n const locale = localized ? change.locale ?? input.locale : undefined\n if (localized && locale === undefined) {\n return issue('missing-localized-value', `Field \"${change.field}\" is localized — provide \"locale\".`)\n }\n\n if (change.blockId !== undefined || change.prop !== undefined) {\n return applyBlockPropChange(doc, field, change, locale, issue)\n }\n\n const mapped = mapUpdateValue(field, change, input.document, input, issue)\n if ('issue' in mapped) return mapped\n return { doc: writeFieldValue(doc, change.field, locale, mapped.value) }\n}\n\n\n/**\n * Build the reviewable update proposal: apply every change over a copy of the\n * document (loud targeting), validate the merged result with the injected\n * leashes (only errors the change INTRODUCES block), and report the semantic\n * diff. `no-change` when the changes resolve to the current values.\n */\nexport function buildUpdateProposal(input: BuildUpdateProposalInput): BuildUpdateProposalResult {\n const { registry, collection, document } = input\n\n let next: CmsDocument = structuredClone(document)\n const targetingIssues: CmsValidationIssue[] = []\n for (const change of input.changes) {\n const outcome = applyOneChange(input, next, change)\n if ('issue' in outcome) targetingIssues.push(outcome.issue)\n else next = outcome.doc\n }\n if (targetingIssues.length > 0) return { ok: false, issues: targetingIssues }\n\n // EC-497: THE bag, whole — no per-call-site reassembly.\n const validateOptions: ValidateDocumentOptions = input.validateOptions ?? {}\n const before = validateDocument(registry, document, validateOptions)\n const issues = validateDocument(registry, next, validateOptions)\n const introduced = introducedErrors(before, issues)\n if (introduced.length > 0) return { ok: false, issues: introduced }\n\n const diff = diffDocuments(collection, document, next)\n if (diff.changes.length === 0) return { ok: true, kind: 'no-change' }\n\n return {\n ok: true,\n kind: 'proposal',\n patch: {\n collection: collection.id,\n id: document.id,\n values: next.values,\n ...(next.localized && Object.keys(next.localized).length > 0\n ? { localized: next.localized }\n : {}),\n },\n before: {\n values: document.values,\n ...(document.localized ? { localized: document.localized } : {}),\n },\n changedFields: diff.changes.map((change) =>\n change.locale !== undefined ? `${change.field} (${change.locale})` : change.field,\n ),\n issues: warningsOf(issues),\n }\n}\n"]}
1
+ {"version":3,"file":"update-fields.js","sourceRoot":"","sources":["../../../src/lib/ai/update-fields.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,OAAO,EACL,QAAQ,EACR,gBAAgB,EAChB,WAAW,EACX,eAAe,EACf,aAAa,EACb,gBAAgB,GACjB,MAAM,0BAA0B,CAAA;AAUjC,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAA;AAExF,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAA;AACvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAA;AACjE,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAA;AACpE,OAAO,EAAE,2BAA2B,EAAE,MAAM,mBAAmB,CAAA;AAuE/D,SAAS,gBAAgB,CAAC,KAAc;IACtC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAA;AACtD,CAAC;AAED;;;;;;GAMG;AACH,SAAS,eAAe,CACtB,GAAgB,EAChB,SAAiB,EACjB,MAA0B,EAC1B,KAAc;IAEd,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QACzB,MAAM,SAAS,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,CA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C,EAAE,CAAC;SACjE;QACD,aAAa,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CACzC,MAAM,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,KAAK,KAAK,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAClF;QACD,MAAM,EAAE,UAAU,CAAC,MAAM,CAAC;KAC3B,CAAA;AACH,CAAC","sourcesContent":["/**\n * `buildUpdateProposal` — the EC-378 update-proposal builder (the edit-flow\n * counterpart of `applyContentWithShape`, minus the generation step).\n *\n * The MODEL authors the field changes directly in the `updateFields` tool input\n * (it has the conversation + `getDocument` output as context); this module turns\n * those changes into a reviewable proposal with the SAME engine discipline the\n * create flow has:\n *\n * - **merge semantics**: changes apply per field over the EXISTING document —\n * never a whole-document rewrite; the patch is the merged document, the diff\n * (`diffDocuments`) is what the editor reviews (changed fields only).\n * - **targeting is addressed with the engine's existing conventions** — field\n * name + optional locale bucket (the diff / `RestoreScope` shape) and, inside\n * a `blocks` field, `blockId` + `prop` (the `BlockChange`/`PropChange` shape,\n * root blocks by stable node id). No new path grammar.\n * - **leashes hold, loudly**: `ai.exclude` fields are untouchable; relation AND\n * asset ids (EC-381) must come from searched candidates (`searchDocuments` /\n * `listAssets`) or already be on the document; every targeting failure is an\n * explicit issue — never a silent drop (unlike the create shape, which makes bad\n * ids structurally unrepresentable, an update change is imperative — so it FAILS\n * instead of being filtered).\n * - **validation parity**: the merged document runs through `validateDocument`\n * with the studio's injected leashes. Only errors the change INTRODUCES block\n * the proposal — pre-existing brokenness on the document is not the\n * assistant's doing and must not force a whole-document repair (the editor's\n * own save path tolerates it the same way; errors gate publish, not drafts).\n *\n * Locale-awareness: a localized field's change lands in the change's `locale`,\n * defaulting to the editor's working locale (`input.locale`). Non-localized\n * fields reject a `locale` loudly.\n *\n * Pure and deterministic — no provider, no I/O; the executor (`tools.ts`) wires\n * it to `getDocument` + the candidate store and hands the result to the review\n * sink.\n */\nimport {\n cmsIssue,\n isFieldLocalized,\n readAssetId,\n readDocumentRef,\n referenceNode,\n validateDocument,\n} from '@elytracms/core/cms-core'\nimport type {\n CmsDocument,\n CmsValidationIssue,\n CollectionDef,\n CollectionRegistry,\n FieldDef,\n FieldValues,\n ValidateDocumentOptions,\n} from '@elytracms/core/cms-core'\nimport { blockRootsOf, editBlockRoots, staticProp } from '@elytracms/core/project-graph'\nimport type { ComponentNode, JsonValue } from '@elytracms/core/project-graph'\nimport { diffDocuments } from '@elytracms/core/content'\nimport { carryAssetPlacements } from '../assets/asset-placements'\nimport { introducedErrors, warningsOf } from './proposal-validation'\nimport { richTextValueFromModelInput } from './rich-text-input'\nimport type { AssetCandidates, ContentPatch, RelationCandidates } from './types'\n\n/**\n * One field change of an `updateFields` proposal, addressed with the engine's\n * existing conventions (diff / restore-scope): `field` (+ `locale` bucket for a\n * localized field), and for a `blocks` field optionally `blockId` + `prop` to\n * change one component prop of one root block. `value` is the new value\n * (`null`/omitted clears the field or prop).\n */\nexport interface UpdateFieldChange {\n field: string\n /** Locale bucket for a LOCALIZED field (defaults to the editor's working locale). */\n locale?: string\n /** For a `blocks` field: the root block's stable node id (from `getDocument`). */\n blockId?: string\n /** With `blockId`: the component prop to change. */\n prop?: string\n /** The new value; `null` / omitted clears the field or prop. */\n value?: unknown\n}\n\nexport interface BuildUpdateProposalInput {\n registry: CollectionRegistry\n collection: CollectionDef\n /** The CURRENT document — the proposal's \"before\" side. Never mutated. */\n document: CmsDocument\n changes: readonly UpdateFieldChange[]\n /** The editor's working locale — the default bucket for localized fields. */\n locale?: string\n /** Relation candidates (searched ids) keyed by field name — the id leash. */\n candidates?: RelationCandidates\n /** Asset candidates (searched library ids) keyed by field name — the asset id leash (EC-381). */\n assetCandidates?: AssetCandidates\n /**\n * THE validation option bag (EC-497) — the studio session's\n * `gateValidateOptions(...)`, whole. It also carries the project's\n * `localeConfig`, which is what the unknown-locale targeting check reads: one\n * source for \"which locales exist\", not two that can disagree.\n */\n validateOptions?: ValidateDocumentOptions\n}\n\n/** The `before` snapshot the review diff renders against. */\nexport interface UpdateBeforeSnapshot {\n values: FieldValues\n localized?: Record<string, FieldValues>\n}\n\nexport type BuildUpdateProposalResult =\n | {\n ok: true\n kind: 'proposal'\n /** The MERGED document as a patch (full values; the diff shows changed fields only). */\n patch: ContentPatch\n before: UpdateBeforeSnapshot\n /** Human-readable descriptors of the changed fields (e.g. `title (de)`). */\n changedFields: string[]\n /** Non-error issues on the accepted result (warnings). */\n issues: CmsValidationIssue[]\n }\n | {\n /** Every change resolved to the current values — nothing to propose. */\n ok: true\n kind: 'no-change'\n }\n | { ok: false; issues: CmsValidationIssue[] }\n\ntype ChangeIssue = { issue: CmsValidationIssue }\ntype ChangeOutcome = { doc: CmsDocument } | ChangeIssue\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0\n}\n\n/**\n * The present/absent-key field write — the same semantics as the editor's\n * single-sourced `setFieldValue` (`lib/locale/fallback`): a resolved `locale`\n * writes the `localized[locale]` bucket, clearing DELETES the key. Local here\n * (not imported) because this module takes the locale as an already-resolved\n * argument per change; the semantics are pinned by tests on both sides.\n */\nfunction writeFieldValue(\n doc: CmsDocument,\n fieldName: string,\n locale: string | undefined,\n value: unknown,\n): CmsDocument {\n if (locale !== undefined) {\n const perLocale = { ...(doc.localized?.[locale] ?? {}) }\n if (value === undefined) delete perLocale[fieldName]\n else perLocale[fieldName] = value\n return { ...doc, localized: { ...doc.localized, [locale]: perLocale } }\n }\n const values = { ...doc.values }\n if (value === undefined) delete values[fieldName]\n else values[fieldName] = value\n return { ...doc, values }\n}\n\n/**\n * The read twin of {@link writeFieldValue}: the field's value in the resolved\n * `locale` bucket, or in the shared `values` for a non-localized field. The exact\n * bucket only, with no default-locale fallback, because that bucket is the one the\n * write replaces.\n */\nfunction readFieldValue(doc: CmsDocument, fieldName: string, locale: string | undefined): unknown {\n return locale !== undefined ? doc.localized?.[locale]?.[fieldName] : doc.values[fieldName]\n}\n\n/** Relation ids CURRENTLY on the document for a field (any bucket) — re-usable without a search. */\nfunction currentRelationIds(doc: CmsDocument, fieldName: string): Set<string> {\n const ids = new Set<string>()\n const collect = (value: unknown) => {\n for (const entry of Array.isArray(value) ? value : [value]) {\n const ref = readDocumentRef(entry)\n if (ref) ids.add(ref.id)\n }\n }\n collect(doc.values[fieldName])\n for (const bucket of Object.values(doc.localized ?? {})) collect(bucket[fieldName])\n return ids\n}\n\n/** Asset ids CURRENTLY on the document for a field (any bucket) — re-usable without a search (EC-381). */\nfunction currentAssetIds(doc: CmsDocument, fieldName: string): Set<string> {\n const ids = new Set<string>()\n const collect = (value: unknown) => {\n for (const entry of Array.isArray(value) ? value : [value]) {\n const id = readAssetId(entry)\n if (id) ids.add(id)\n }\n }\n collect(doc.values[fieldName])\n for (const bucket of Object.values(doc.localized ?? {})) collect(bucket[fieldName])\n return ids\n}\n\n/**\n * Map a change's raw value into the stored value shape (envelopes; loud leash).\n * `document` is the ORIGINAL document, which is what the id leash reads. `current`\n * is the value this change replaces, taken from the resolved locale bucket of the\n * working copy. The asset sub-field carry reads it (EC-558).\n */\nfunction mapUpdateValue(\n field: FieldDef,\n change: UpdateFieldChange,\n document: CmsDocument,\n current: unknown,\n input: BuildUpdateProposalInput,\n issue: (code: Parameters<typeof cmsIssue>[0]['code'], message: string) => ChangeIssue,\n): { value: unknown } | ChangeIssue {\n const raw = change.value\n if (raw === undefined || raw === null) return { value: undefined } // clear\n switch (field.type) {\n case 'relation': {\n const ids = Array.isArray(raw) ? raw : [raw]\n if (!ids.every(isNonEmptyString)) {\n return issue(\n 'invalid-field-value',\n `Relation \"${field.name}\" takes document id string(s) from searchDocuments results.`,\n )\n }\n // The id leash (same stance as the create enum, but LOUD): only searched\n // candidate ids or ids already on the document are usable.\n const allowed = new Set([\n ...(input.candidates?.[field.name] ?? []).map((c) => c.id),\n ...currentRelationIds(document, field.name),\n ])\n const unknown = ids.filter((id) => !allowed.has(id))\n if (unknown.length > 0) {\n return issue(\n 'unknown-relation-target',\n `Relation \"${field.name}\" may only use ids from searchDocuments results — search \"${field.target}\" first (got: ${unknown.join(', ')}).`,\n )\n }\n if (!field.multiple && ids.length > 1) {\n return issue('invalid-field-value', `Field \"${field.name}\" holds a single reference — pass one id.`)\n }\n const refs = ids.map((id) => referenceNode({ collection: field.target, id }))\n return { value: field.multiple ? refs : refs[0] }\n }\n case 'asset': {\n const ids = Array.isArray(raw) ? raw : [raw]\n if (!ids.every(isNonEmptyString)) {\n return issue(\n 'invalid-field-value',\n `Asset field \"${field.name}\" takes asset id string(s) from listAssets results.`,\n )\n }\n // EC-381 — the asset id leash (same stance as relations, but LOUD): only\n // searched library candidate ids or ids already on the document are usable;\n // the assistant never invents or uploads an asset.\n const allowed = new Set([\n ...(input.assetCandidates?.[field.name] ?? []).map((c) => c.id),\n ...currentAssetIds(document, field.name),\n ])\n const unknown = ids.filter((id) => !allowed.has(id))\n if (unknown.length > 0) {\n return issue(\n 'unknown-asset',\n `Asset field \"${field.name}\" may only use ids from listAssets results — search the media library first (got: ${unknown.join(', ')}).`,\n )\n }\n if (!field.multiple && ids.length > 1) {\n return issue('invalid-field-value', `Field \"${field.name}\" holds a single asset — pass one id.`)\n }\n // EC-558: replace-with-list through the one carry rule. A held id keeps its\n // placement's per-use sub-fields (a caption, say), a single swap carries\n // them to the new image, and a NEW id is an envelope (EC-381). Data about\n // the image itself (alt, an AI flag) belongs on the asset's `meta`.\n return {\n value: carryAssetPlacements(\n current,\n field.multiple ? { multiple: true, ids } : { multiple: false, id: ids[0] ?? null },\n 'envelope',\n ),\n }\n }\n case 'richText': {\n // EC-379: a string value is MARKDOWN, converted through the engine's strict\n // subset converter; out-of-subset constructs fail LOUD (the model retries\n // in-conversation). A `{ version, doc }` envelope object stays accepted for\n // robustness (getDocument may have shown one) — see rich-text-input.ts.\n const converted = richTextValueFromModelInput(raw)\n if (!converted.ok) {\n return issue('invalid-field-value', `Field \"${field.name}\": ${converted.problems.join(' ')}`)\n }\n return { value: converted.value }\n }\n default:\n // text / number / boolean / date / select / object / blocks: as-is\n // (the merged document's validateDocument run is the shape leash).\n return { value: raw }\n }\n}\n\n/** Change one component prop of one root block (the `BlockChange`/`PropChange` address). */\nfunction applyBlockPropChange(\n doc: CmsDocument,\n field: FieldDef,\n change: UpdateFieldChange,\n locale: string | undefined,\n issue: (code: Parameters<typeof cmsIssue>[0]['code'], message: string) => ChangeIssue,\n): ChangeOutcome {\n if (field.type !== 'blocks') {\n return issue(\n 'invalid-field-value',\n `\"${change.field}\" is not a blocks field — omit \"blockId\"/\"prop\" (set the field value directly).`,\n )\n }\n if (!isNonEmptyString(change.blockId)) {\n return issue(\n 'invalid-field-value',\n `Changing a block on \"${change.field}\" needs \"blockId\" — block ids come from getDocument.`,\n )\n }\n if (!isNonEmptyString(change.prop)) {\n return issue(\n 'invalid-field-value',\n `Changing block \"${change.blockId}\" needs \"prop\" — the component property to change.`,\n )\n }\n const original = readFieldValue(doc, change.field, locale)\n const blocks = blockRootsOf(original)\n const index = blocks.findIndex((block) => block.id === change.blockId)\n if (index < 0) {\n return issue(\n 'invalid-field-value',\n `Block \"${change.blockId}\" was not found on \"${change.field}\" — read the document first; block ids come from getDocument.`,\n )\n }\n const block = blocks[index]!\n const props = { ...(block.props ?? {}) }\n if (change.value === undefined || change.value === null) delete props[change.prop]\n else props[change.prop] = staticProp(change.value as JsonValue)\n const nextBlock: ComponentNode = { ...block, props }\n // EC-576: through the core write path — the other roots and every typography\n // item keep their place, and the write is the v2 sequence. (`blocks` is\n // `editBlockRoots`' own root list, so `index` addresses the same root.)\n const value = editBlockRoots(original, (roots) => roots.map((b, i) => (i === index ? nextBlock : b)))\n return { doc: writeFieldValue(doc, change.field, locale, value) }\n}\n\n/** Apply ONE change to a (copy of the) document, or report the targeting issue. */\nfunction applyOneChange(\n input: BuildUpdateProposalInput,\n doc: CmsDocument,\n change: UpdateFieldChange,\n): ChangeOutcome {\n const { collection } = input\n const issue = (\n code: Parameters<typeof cmsIssue>[0]['code'],\n message: string,\n ): ChangeIssue => ({\n issue: cmsIssue({\n code,\n message,\n path: ['documents', `${collection.id}:${doc.id}`, 'values', change.field],\n collectionId: collection.id,\n documentId: doc.id,\n meta: { field: change.field, ...(change.locale !== undefined ? { locale: change.locale } : {}) },\n }),\n })\n\n const field = collection.fields.find((f) => f.name === change.field)\n if (!field) {\n return issue(\n 'invalid-field-value',\n `Unknown field \"${change.field}\" on collection \"${collection.id}\" — use a field name from the schema.`,\n )\n }\n if (field.ai?.exclude) {\n return issue('invalid-field-value', `Field \"${change.field}\" must not be edited by the assistant.`)\n }\n\n const localized = isFieldLocalized(collection, change.field)\n if (!localized && change.locale !== undefined) {\n return issue('unknown-locale', `Field \"${change.field}\" is not localized — omit \"locale\".`)\n }\n if (\n change.locale !== undefined &&\n input.validateOptions?.localeConfig &&\n !input.validateOptions.localeConfig.locales.includes(change.locale)\n ) {\n return issue(\n 'unknown-locale',\n `Unknown locale \"${change.locale}\" — this project has: ${input.validateOptions?.localeConfig?.locales.join(', ')}.`,\n )\n }\n const locale = localized ? change.locale ?? input.locale : undefined\n if (localized && locale === undefined) {\n return issue('missing-localized-value', `Field \"${change.field}\" is localized — provide \"locale\".`)\n }\n\n if (change.blockId !== undefined || change.prop !== undefined) {\n return applyBlockPropChange(doc, field, change, locale, issue)\n }\n\n const current = readFieldValue(doc, change.field, locale)\n const mapped = mapUpdateValue(field, change, input.document, current, input, issue)\n if ('issue' in mapped) return mapped\n return { doc: writeFieldValue(doc, change.field, locale, mapped.value) }\n}\n\n\n/**\n * Build the reviewable update proposal: apply every change over a copy of the\n * document (loud targeting), validate the merged result with the injected\n * leashes (only errors the change INTRODUCES block), and report the semantic\n * diff. `no-change` when the changes resolve to the current values.\n */\nexport function buildUpdateProposal(input: BuildUpdateProposalInput): BuildUpdateProposalResult {\n const { registry, collection, document } = input\n\n let next: CmsDocument = structuredClone(document)\n const targetingIssues: CmsValidationIssue[] = []\n for (const change of input.changes) {\n const outcome = applyOneChange(input, next, change)\n if ('issue' in outcome) targetingIssues.push(outcome.issue)\n else next = outcome.doc\n }\n if (targetingIssues.length > 0) return { ok: false, issues: targetingIssues }\n\n // EC-497: THE bag, whole — no per-call-site reassembly.\n const validateOptions: ValidateDocumentOptions = input.validateOptions ?? {}\n const before = validateDocument(registry, document, validateOptions)\n const issues = validateDocument(registry, next, validateOptions)\n const introduced = introducedErrors(before, issues)\n if (introduced.length > 0) return { ok: false, issues: introduced }\n\n const diff = diffDocuments(collection, document, next)\n if (diff.changes.length === 0) return { ok: true, kind: 'no-change' }\n\n return {\n ok: true,\n kind: 'proposal',\n patch: {\n collection: collection.id,\n id: document.id,\n values: next.values,\n ...(next.localized && Object.keys(next.localized).length > 0\n ? { localized: next.localized }\n : {}),\n },\n before: {\n values: document.values,\n ...(document.localized ? { localized: document.localized } : {}),\n },\n changedFields: diff.changes.map((change) =>\n change.locale !== undefined ? `${change.field} (${change.locale})` : change.field,\n ),\n issues: warningsOf(issues),\n }\n}\n"]}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * How a writer spells a BRAND-NEW placement, which has no sub-fields yet. This is
3
+ * the caller's choice, not part of the carry rule. The detail editor and the table
4
+ * cell use `'bare'` on a field without sub-fields and `'envelope'` on one with them
5
+ * (`assetPickForm`). AI always uses `'envelope'` (EC-381).
6
+ */
7
+ export type NewPlacementForm = 'bare' | 'envelope';
8
+ /** The ids the field should hold next. The shape follows the field's cardinality. */
9
+ export type AssetPlacementTarget = {
10
+ multiple: false;
11
+ id: string | null;
12
+ } | {
13
+ multiple: true;
14
+ ids: readonly string[];
15
+ };
16
+ /**
17
+ * Return the field's next value with every placement's per-use sub-fields kept.
18
+ *
19
+ * - **Single field.** The placement's sub-fields carry over to whatever id now fills
20
+ * it, so swapping the image keeps the caption. Re-picking the same id is a no-op,
21
+ * and `null` clears the field (`undefined`).
22
+ * - **Multiple field.** An id the value already held keeps its entry verbatim, with
23
+ * its sub-fields and its form (a bare id stays bare). Entries are matched in order,
24
+ * so an image placed twice keeps both placements. An id the value did not hold
25
+ * becomes a new placement in `form`. A held entry whose id is not in `ids` is
26
+ * removed.
27
+ *
28
+ * The rule carries every key except `type`/`id`, the same set that `assetSubfieldsOf`
29
+ * reads. That includes keys the config no longer declares (AD-14: the schema is a
30
+ * lens, so a writer never deletes what the lens does not show).
31
+ *
32
+ * When nothing changes it returns `current` itself (the same reference), so a caller
33
+ * can skip the write.
34
+ */
35
+ export declare function carryAssetPlacements(current: unknown, next: AssetPlacementTarget, form: NewPlacementForm): unknown;
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The per-use sub-field carry rule for an asset field's value (EC-558).
3
+ *
4
+ * An asset field that declares per-use sub-fields (EC-301) stores envelopes such as
5
+ * `{ type: 'asset', id, caption }`. Those sub-fields are PLACEMENT data: they
6
+ * describe this use of the image, not the image itself (owner ruling 2026-09-26;
7
+ * data that describes the image belongs on the asset record's `meta`). A writer
8
+ * that changes which image a placement shows must therefore keep the placement's
9
+ * sub-fields. Before EC-558 only the detail editor did that. The table cell and AI
10
+ * `updateFields` rebuilt the value from bare ids and lost them.
11
+ *
12
+ * {@link carryAssetPlacements} is the one declaration of that rule. Two operations
13
+ * go through it:
14
+ * - **append / pick**: the table cell and the detail editor
15
+ * (`applyAssetSelection` / `appendAssetSelections` in
16
+ * `components/assets/asset-selection.ts`). The next list is the held list plus
17
+ * the picked ids, and a single field swaps its one placement's image.
18
+ * - **replace-with-list**: AI `updateFields` (`lib/ai/update-fields.ts`). The next
19
+ * list is the list the model sent.
20
+ *
21
+ * It lives in `lib/` because `lib/ai` may not import from `components/`, and both
22
+ * sides need it. Its only dependency is `@elytracms/core/cms-core`, so the AI host
23
+ * route pulls in nothing from the browser. Its natural home is next to `assetNode`
24
+ * in `core/cms-core/envelopes.ts`. Move it there if a writer outside the studio
25
+ * (import, CLI, MCP) appears.
26
+ */
27
+ import { assetNode, assetSubfieldsOf, readAssetId } from '@elytracms/core/cms-core';
28
+ function newPlacement(id, form) {
29
+ return form === 'envelope' ? assetNode(id) : id;
30
+ }
31
+ /**
32
+ * Return the field's next value with every placement's per-use sub-fields kept.
33
+ *
34
+ * - **Single field.** The placement's sub-fields carry over to whatever id now fills
35
+ * it, so swapping the image keeps the caption. Re-picking the same id is a no-op,
36
+ * and `null` clears the field (`undefined`).
37
+ * - **Multiple field.** An id the value already held keeps its entry verbatim, with
38
+ * its sub-fields and its form (a bare id stays bare). Entries are matched in order,
39
+ * so an image placed twice keeps both placements. An id the value did not hold
40
+ * becomes a new placement in `form`. A held entry whose id is not in `ids` is
41
+ * removed.
42
+ *
43
+ * The rule carries every key except `type`/`id`, the same set that `assetSubfieldsOf`
44
+ * reads. That includes keys the config no longer declares (AD-14: the schema is a
45
+ * lens, so a writer never deletes what the lens does not show).
46
+ *
47
+ * When nothing changes it returns `current` itself (the same reference), so a caller
48
+ * can skip the write.
49
+ */
50
+ export function carryAssetPlacements(current, next, form) {
51
+ if (!next.multiple) {
52
+ if (next.id === null)
53
+ return undefined;
54
+ // `singleAssetIdOf` tolerates a legacy one-item array on a single field, so read
55
+ // its placement the same way.
56
+ const held = Array.isArray(current) ? current[0] : current;
57
+ if (readAssetId(held) === next.id)
58
+ return current;
59
+ const subfields = assetSubfieldsOf(held);
60
+ return Object.keys(subfields).length > 0 ? assetNode(next.id, subfields) : newPlacement(next.id, form);
61
+ }
62
+ const held = Array.isArray(current) ? current : [];
63
+ const used = new Set();
64
+ const out = next.ids.map((id) => {
65
+ const index = held.findIndex((entry, i) => !used.has(i) && readAssetId(entry) === id);
66
+ if (index < 0)
67
+ return newPlacement(id, form);
68
+ used.add(index);
69
+ return held[index];
70
+ });
71
+ const unchanged = out.length === held.length && out.every((entry, i) => entry === held[i]);
72
+ return unchanged && Array.isArray(current) ? current : out;
73
+ }
74
+ //# sourceMappingURL=asset-placements.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asset-placements.js","sourceRoot":"","sources":["../../../src/lib/assets/asset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I,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE;QAC9B,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,WAAW,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,CAAA;QACrF,IAAI,KAAK,GAAG,CAAC;YAAE,OAAO,YAAY,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;QAC5C,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QACf,OAAO,IAAI,CAAC,KAAK,CAAC,CAAA;IACpB,CAAC,CAAC,CAAA;IACF,MAAM,SAAS,GAAG,GAAG,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;IAC1F,OAAO,SAAS,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAA;AAC5D,CAAC","sourcesContent":["/**\n * The per-use sub-field carry rule for an asset field's value (EC-558).\n *\n * An asset field that declares per-use sub-fields (EC-301) stores envelopes such as\n * `{ type: 'asset', id, caption }`. Those sub-fields are PLACEMENT data: they\n * describe this use of the image, not the image itself (owner ruling 2026-09-26;\n * data that describes the image belongs on the asset record's `meta`). A writer\n * that changes which image a placement shows must therefore keep the placement's\n * sub-fields. Before EC-558 only the detail editor did that. The table cell and AI\n * `updateFields` rebuilt the value from bare ids and lost them.\n *\n * {@link carryAssetPlacements} is the one declaration of that rule. Two operations\n * go through it:\n * - **append / pick**: the table cell and the detail editor\n * (`applyAssetSelection` / `appendAssetSelections` in\n * `components/assets/asset-selection.ts`). The next list is the held list plus\n * the picked ids, and a single field swaps its one placement's image.\n * - **replace-with-list**: AI `updateFields` (`lib/ai/update-fields.ts`). The next\n * list is the list the model sent.\n *\n * It lives in `lib/` because `lib/ai` may not import from `components/`, and both\n * sides need it. Its only dependency is `@elytracms/core/cms-core`, so the AI host\n * route pulls in nothing from the browser. Its natural home is next to `assetNode`\n * in `core/cms-core/envelopes.ts`. Move it there if a writer outside the studio\n * (import, CLI, MCP) appears.\n */\nimport { assetNode, assetSubfieldsOf, readAssetId } from '@elytracms/core/cms-core'\n\n/**\n * How a writer spells a BRAND-NEW placement, which has no sub-fields yet. This is\n * the caller's choice, not part of the carry rule. The detail editor and the table\n * cell use `'bare'` on a field without sub-fields and `'envelope'` on one with them\n * (`assetPickForm`). AI always uses `'envelope'` (EC-381).\n */\nexport type NewPlacementForm = 'bare' | 'envelope'\n\n/** The ids the field should hold next. The shape follows the field's cardinality. */\nexport type AssetPlacementTarget =\n | { multiple: false; id: string | null }\n | { multiple: true; ids: readonly string[] }\n\nfunction newPlacement(id: string, form: NewPlacementForm): unknown {\n return form === 'envelope' ? assetNode(id) : id\n}\n\n/**\n * Return the field's next value with every placement's per-use sub-fields kept.\n *\n * - **Single field.** The placement's sub-fields carry over to whatever id now fills\n * it, so swapping the image keeps the caption. Re-picking the same id is a no-op,\n * and `null` clears the field (`undefined`).\n * - **Multiple field.** An id the value already held keeps its entry verbatim, with\n * its sub-fields and its form (a bare id stays bare). Entries are matched in order,\n * so an image placed twice keeps both placements. An id the value did not hold\n * becomes a new placement in `form`. A held entry whose id is not in `ids` is\n * removed.\n *\n * The rule carries every key except `type`/`id`, the same set that `assetSubfieldsOf`\n * reads. That includes keys the config no longer declares (AD-14: the schema is a\n * lens, so a writer never deletes what the lens does not show).\n *\n * When nothing changes it returns `current` itself (the same reference), so a caller\n * can skip the write.\n */\nexport function carryAssetPlacements(\n current: unknown,\n next: AssetPlacementTarget,\n form: NewPlacementForm,\n): unknown {\n if (!next.multiple) {\n if (next.id === null) return undefined\n // `singleAssetIdOf` tolerates a legacy one-item array on a single field, so read\n // its placement the same way.\n const held = Array.isArray(current) ? current[0] : current\n if (readAssetId(held) === next.id) return current\n const subfields = assetSubfieldsOf(held)\n return Object.keys(subfields).length > 0 ? assetNode(next.id, subfields) : newPlacement(next.id, form)\n }\n\n const held = Array.isArray(current) ? (current as unknown[]) : []\n const used = new Set<number>()\n const out = next.ids.map((id) => {\n const index = held.findIndex((entry, i) => !used.has(i) && readAssetId(entry) === id)\n if (index < 0) return newPlacement(id, form)\n used.add(index)\n return held[index]\n })\n const unchanged = out.length === held.length && out.every((entry, i) => entry === held[i])\n return unchanged && Array.isArray(current) ? current : out\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { AssetRecord, AssetRepository, BlobStorageAdapter, NewAssetInput } from '@elytracms/core/persistence';
1
+ import type { AssetRecord, AssetRepository, AssetWriteInput, BlobStorageAdapter } from '@elytracms/core/persistence';
2
2
  import type { GeneratedVariants, ThumbSource, VariantWant } from './thumbnail.js';
3
3
  /**
4
4
  * The assets that still need at least one variant (pure, node-tested idempotence
@@ -10,14 +10,15 @@ export declare function assetsNeedingVariants(assets: readonly AssetRecord[]): A
10
10
  /** The variants an asset is missing — what the per-variant backfill asks the encoder for. */
11
11
  export declare function variantWantFor(asset: AssetRecord): VariantWant;
12
12
  /**
13
- * The full upsert input that re-states an existing record with freshly generated
14
- * variants attached — the targeted patch path for the backfill, within the
15
- * existing repository/`assets.upsert` contract (EC-400 AD-4 / EC-420). Mirrors
16
- * `assetMetadataUpsertInput`: every current column is restated so the full-replace
17
- * upsert preserves it. A newly generated variant overlays; a variant the record
18
- * ALREADY had (the other half of a per-variant fill) is preserved from `current`.
13
+ * The asset write for a backfill result (EC-400 AD-4 / EC-420, EC-577): ONLY the
14
+ * variants just generated. Every other column is absent, so it keeps its stored
15
+ * value — including a variant the record already had (the other half of a
16
+ * per-variant fill) and any metadata an editor saved while the run was going. The
17
+ * restate this replaced wrote the whole listed record back, which overwrote such
18
+ * a concurrent edit with the stale listing — and re-created an asset deleted
19
+ * mid-run; now a write for a vanished asset is refused and counted `failed`.
19
20
  */
20
- export declare function assetVariantUpsertInput(current: AssetRecord, variants: GeneratedVariants): NewAssetInput;
21
+ export declare function assetVariantWrite(assetId: string, variants: GeneratedVariants): AssetWriteInput;
21
22
  /** Live tally the "Generate previews" UI renders (EC-400 AD-1). */
22
23
  export interface BackfillProgress {
23
24
  /** How many assets need at least one variant (the candidate set size). */
@@ -14,7 +14,7 @@ import { generateVariants, planLqip, planThumb } from './thumbnail.js';
14
14
  * The write goes through the injected {@link AssetRepository} — in the studio the
15
15
  * EC-141 operations facade — so the patch flows through the one operations layer /
16
16
  * TanStack Query cache (AD-5 / AD-17), never a direct backend client. The pure
17
- * cores ({@link assetsNeedingVariants}, {@link assetVariantUpsertInput}) are
17
+ * cores ({@link assetsNeedingVariants}, {@link assetVariantWrite}) are
18
18
  * node-tested; the byte fetch + canvas encode stay in the injectable shell.
19
19
  */
20
20
  /** An image record still missing a thumb whose {@link planThumb} decision is `encode`. */
@@ -39,31 +39,19 @@ export function variantWantFor(asset) {
39
39
  return { thumb: needsThumb(asset), lqip: needsLqip(asset) };
40
40
  }
41
41
  /**
42
- * The full upsert input that re-states an existing record with freshly generated
43
- * variants attached — the targeted patch path for the backfill, within the
44
- * existing repository/`assets.upsert` contract (EC-400 AD-4 / EC-420). Mirrors
45
- * `assetMetadataUpsertInput`: every current column is restated so the full-replace
46
- * upsert preserves it. A newly generated variant overlays; a variant the record
47
- * ALREADY had (the other half of a per-variant fill) is preserved from `current`.
42
+ * The asset write for a backfill result (EC-400 AD-4 / EC-420, EC-577): ONLY the
43
+ * variants just generated. Every other column is absent, so it keeps its stored
44
+ * value — including a variant the record already had (the other half of a
45
+ * per-variant fill) and any metadata an editor saved while the run was going. The
46
+ * restate this replaced wrote the whole listed record back, which overwrote such
47
+ * a concurrent edit with the stale listing — and re-created an asset deleted
48
+ * mid-run; now a write for a vanished asset is refused and counted `failed`.
48
49
  */
49
- export function assetVariantUpsertInput(current, variants) {
50
- const thumb = variants.thumb ?? current.thumb;
51
- const lqip = variants.lqip ?? current.lqip;
50
+ export function assetVariantWrite(assetId, variants) {
52
51
  return {
53
- id: current.id,
54
- filename: current.filename,
55
- contentType: current.contentType,
56
- byteSize: current.byteSize,
57
- storageKey: current.storageKey,
58
- ...(current.width !== undefined ? { width: current.width } : {}),
59
- ...(current.height !== undefined ? { height: current.height } : {}),
60
- ...(current.url !== undefined ? { url: current.url } : {}),
61
- ...(current.alt !== undefined ? { alt: current.alt } : {}),
62
- ...(current.title !== undefined ? { title: current.title } : {}),
63
- ...(current.focalPoint !== undefined ? { focalPoint: current.focalPoint } : {}),
64
- ...(current.meta !== undefined ? { meta: current.meta } : {}),
65
- ...(thumb !== undefined ? { thumb } : {}),
66
- ...(lqip !== undefined ? { lqip } : {}),
52
+ id: assetId,
53
+ ...(variants.thumb !== undefined ? { thumb: variants.thumb } : {}),
54
+ ...(variants.lqip !== undefined ? { lqip: variants.lqip } : {}),
67
55
  };
68
56
  }
69
57
  /**
@@ -102,7 +90,7 @@ export async function runVariantBackfill(deps, projectId) {
102
90
  progress.skipped += 1;
103
91
  }
104
92
  else {
105
- const patched = await deps.assets.upsertAsset(projectId, assetVariantUpsertInput(asset, variants));
93
+ const patched = await deps.assets.upsertAsset(projectId, assetVariantWrite(asset.id, variants));
106
94
  deps.onGenerated?.(patched);
107
95
  progress.generated += 1;
108
96
  }
@@ -1 +1 @@
1
- {"version":3,"file":"backfill-thumbs.js","sourceRoot":"","sources":["../../../src/lib/assets/backfill-thumbs.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAGnE;;;;;;;;;;;;;;;;;GAiBG;AAEH,0FAA0F;AAC1F,SAAS,UAAU,CAAC,KAAkB;IACpC,OAAO,KAAK,CAAC,KAAK,KAAK,SAAS,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAA;AACxE,CAAC;AAED,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AC;oBAC5D,GAAG,CAAC,KAAK,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBAChE,EACD,cAAc,CAAC,KAAK,CAAC,CACtB,CAAA;gBACD,IAAI,QAAQ,CAAC,KAAK,KAAK,SAAS,IAAI,QAAQ,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;oBAChE,QAAQ,CAAC,OAAO,IAAI,CAAC,CAAA;gBACvB,CAAC;qBAAM,CAAC;oBACN,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,SAAS,EAAE,uBAAuB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAA;oBAClG,IAAI,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,CAAA;oBAC3B,QAAQ,CAAC,SAAS,IAAI,CAAC,CAAA;gBACzB,CAAC;YACH,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,QAAQ,CAAC,MAAM,IAAI,CAAC,CAAA;QACtB,CAAC;QACD,QAAQ,CAAC,IAAI,IAAI,CAAC,CAAA;QAClB,IAAI,CAAC,UAAU,EAAE,CAAC,EAAE,GAAG,QAAQ,EAAE,CAAC,CAAA;IACpC,CAAC;IAED,IAAI,CAAC,UAAU,EAAE,CAAC,EAAE,GAAG,QAAQ,EAAE,CAAC,CAAA;IAClC,OAAO,QAAQ,CAAA;AACjB,CAAC","sourcesContent":["import type {\n AssetRecord,\n AssetRepository,\n BlobStorageAdapter,\n NewAssetInput,\n} from '@elytracms/core/persistence'\nimport { generateVariants, planLqip, planThumb } from './thumbnail'\nimport type { GeneratedVariants, ThumbSource, VariantWant } from './thumbnail'\n\n/**\n * The assets-rail \"Generate previews\" backfill (EC-400 AD-1 + EC-420 AD-4).\n * Existing libraries predate the upload-time previews, so an explicit,\n * deterministic maintenance action fetches each original ONCE, runs the SAME\n * decode path as upload, and patches the record. It is idempotent PER VARIANT\n * (EC-420 AD-4): an asset needing only the lqip gets one fetch of the original\n * and fills just what's missing; an asset that already has both is skipped;\n * non-images / SVGs / (for the thumb) already-small images never qualify. The run\n * is sequential with visible progress and cancellable. Opportunistic per-open\n * generation was REJECTED (it hides egress in random editor sessions and is\n * untestable).\n *\n * The write goes through the injected {@link AssetRepository} — in the studio the\n * EC-141 operations facade — so the patch flows through the one operations layer /\n * TanStack Query cache (AD-5 / AD-17), never a direct backend client. The pure\n * cores ({@link assetsNeedingVariants}, {@link assetVariantUpsertInput}) are\n * node-tested; the byte fetch + canvas encode stay in the injectable shell.\n */\n\n/** An image record still missing a thumb whose {@link planThumb} decision is `encode`. */\nfunction needsThumb(asset: AssetRecord): boolean {\n return asset.thumb === undefined && planThumb(asset).kind === 'encode'\n}\n\n/** An image record still missing an lqip whose {@link planLqip} decision is `encode`. */\nfunction needsLqip(asset: AssetRecord): boolean {\n return asset.lqip === undefined && planLqip(asset).kind === 'encode'\n}\n\n/**\n * The assets that still need at least one variant (pure, node-tested idempotence\n * core, EC-420 AD-4): an image record missing a needed thumb OR a needed lqip.\n * Records already carrying both, non-images, SVGs, and (for the thumb) already-\n * small images are silently excluded — re-running on a done library is a no-op.\n */\nexport function assetsNeedingVariants(assets: readonly AssetRecord[]): AssetRecord[] {\n return assets.filter((asset) => needsThumb(asset) || needsLqip(asset))\n}\n\n/** The variants an asset is missing — what the per-variant backfill asks the encoder for. */\nexport function variantWantFor(asset: AssetRecord): VariantWant {\n return { thumb: needsThumb(asset), lqip: needsLqip(asset) }\n}\n\n/**\n * The full upsert input that re-states an existing record with freshly generated\n * variants attached — the targeted patch path for the backfill, within the\n * existing repository/`assets.upsert` contract (EC-400 AD-4 / EC-420). Mirrors\n * `assetMetadataUpsertInput`: every current column is restated so the full-replace\n * upsert preserves it. A newly generated variant overlays; a variant the record\n * ALREADY had (the other half of a per-variant fill) is preserved from `current`.\n */\nexport function assetVariantUpsertInput(\n current: AssetRecord,\n variants: GeneratedVariants,\n): NewAssetInput {\n const thumb = variants.thumb ?? current.thumb\n const lqip = variants.lqip ?? current.lqip\n return {\n id: current.id,\n filename: current.filename,\n contentType: current.contentType,\n byteSize: current.byteSize,\n storageKey: current.storageKey,\n ...(current.width !== undefined ? { width: current.width } : {}),\n ...(current.height !== undefined ? { height: current.height } : {}),\n ...(current.url !== undefined ? { url: current.url } : {}),\n ...(current.alt !== undefined ? { alt: current.alt } : {}),\n ...(current.title !== undefined ? { title: current.title } : {}),\n ...(current.focalPoint !== undefined ? { focalPoint: current.focalPoint } : {}),\n ...(current.meta !== undefined ? { meta: current.meta } : {}),\n ...(thumb !== undefined ? { thumb } : {}),\n ...(lqip !== undefined ? { lqip } : {}),\n }\n}\n\n/** Live tally the \"Generate previews\" UI renders (EC-400 AD-1). */\nexport interface BackfillProgress {\n /** How many assets need at least one variant (the candidate set size). */\n total: number\n /** How many candidates have been processed (generated + skipped + failed). */\n done: number\n /** How many candidates had at least one variant generated and patched in. */\n generated: number\n /** Candidates the re-plan/encode declined (e.g. undecodable) — silent, valid. */\n skipped: number\n /** Candidates whose fetch/encode/patch errored — surfaced, not fatal. */\n failed: number\n /** Filename of the asset currently in flight (for the progress label). */\n current?: string\n /** Set once the run stops early because the caller cancelled. */\n cancelled?: boolean\n}\n\n/** A mutable cancellation flag the UI flips to stop the sequential run (AD-1). */\nexport interface BackfillSignal {\n cancelled: boolean\n}\n\nexport interface BackfillDeps {\n /** Metadata reads + the variant patch write (the operations facade in the studio). */\n assets: AssetRepository\n /** Blob boundary: fetch each original's bytes, store the thumb variant. */\n blobs: BlobStorageAdapter\n /**\n * Injectable variant producer; defaults to {@link generateVariants} over `blobs`.\n * Receives the per-asset `want` so it produces ONLY the missing variants. Tests\n * pass a deterministic fake so the iterator runs in node.\n */\n generate?: (source: Blob, meta: ThumbSource, want: VariantWant) => Promise<GeneratedVariants>\n /** Fired with each patched record so the caller can update its cache in place. */\n onGenerated?: (asset: AssetRecord) => void\n /** Fired after each candidate (and once at the end) to drive the progress UI. */\n onProgress?: (progress: BackfillProgress) => void\n /** Cooperative cancellation — checked before each candidate (AD-1). */\n signal?: BackfillSignal\n}\n\n/**\n * Run the backfill sequentially over a project's images that still need a variant.\n * Resolves with the final tally; never throws (per-asset failures are counted, not\n * fatal). One fetch per candidate serves both variants; only the missing ones are\n * (re)generated (EC-420 AD-4), so an asset with a thumb but no lqip is patched with\n * just the lqip and its existing thumb blob is left untouched.\n */\nexport async function runVariantBackfill(\n deps: BackfillDeps,\n projectId: string,\n): Promise<BackfillProgress> {\n const all = await deps.assets.listAssets(projectId)\n const candidates = assetsNeedingVariants(all)\n const generate =\n deps.generate ??\n ((source: Blob, meta: ThumbSource, want: VariantWant) =>\n generateVariants({ blobs: deps.blobs }, source, meta, want))\n\n const progress: BackfillProgress = { total: candidates.length, done: 0, generated: 0, skipped: 0, failed: 0 }\n deps.onProgress?.({ ...progress })\n\n for (const asset of candidates) {\n if (deps.signal?.cancelled) {\n progress.cancelled = true\n break\n }\n deps.onProgress?.({ ...progress, current: asset.filename })\n try {\n const bytes = await deps.blobs.get(asset.storageKey)\n if (!bytes) {\n progress.failed += 1\n } else {\n const source = new Blob([bytes as BlobPart], { type: asset.contentType })\n const variants = await generate(\n source,\n {\n contentType: asset.contentType,\n ...(asset.width !== undefined ? { width: asset.width } : {}),\n ...(asset.height !== undefined ? { height: asset.height } : {}),\n },\n variantWantFor(asset),\n )\n if (variants.thumb === undefined && variants.lqip === undefined) {\n progress.skipped += 1\n } else {\n const patched = await deps.assets.upsertAsset(projectId, assetVariantUpsertInput(asset, variants))\n deps.onGenerated?.(patched)\n progress.generated += 1\n }\n }\n } catch {\n progress.failed += 1\n }\n progress.done += 1\n deps.onProgress?.({ ...progress })\n }\n\n deps.onProgress?.({ ...progress })\n return progress\n}\n"]}
1
+ {"version":3,"file":"backfill-thumbs.js","sourceRoot":"","sources":["../../../src/lib/assets/backfill-thumbs.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,gBAAgB,E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ssetRecord,\n AssetRepository,\n AssetWriteInput,\n BlobStorageAdapter,\n} from '@elytracms/core/persistence'\nimport { generateVariants, planLqip, planThumb } from './thumbnail'\nimport type { GeneratedVariants, ThumbSource, VariantWant } from './thumbnail'\n\n/**\n * The assets-rail \"Generate previews\" backfill (EC-400 AD-1 + EC-420 AD-4).\n * Existing libraries predate the upload-time previews, so an explicit,\n * deterministic maintenance action fetches each original ONCE, runs the SAME\n * decode path as upload, and patches the record. It is idempotent PER VARIANT\n * (EC-420 AD-4): an asset needing only the lqip gets one fetch of the original\n * and fills just what's missing; an asset that already has both is skipped;\n * non-images / SVGs / (for the thumb) already-small images never qualify. The run\n * is sequential with visible progress and cancellable. Opportunistic per-open\n * generation was REJECTED (it hides egress in random editor sessions and is\n * untestable).\n *\n * The write goes through the injected {@link AssetRepository} — in the studio the\n * EC-141 operations facade — so the patch flows through the one operations layer /\n * TanStack Query cache (AD-5 / AD-17), never a direct backend client. The pure\n * cores ({@link assetsNeedingVariants}, {@link assetVariantWrite}) are\n * node-tested; the byte fetch + canvas encode stay in the injectable shell.\n */\n\n/** An image record still missing a thumb whose {@link planThumb} decision is `encode`. */\nfunction needsThumb(asset: AssetRecord): boolean {\n return asset.thumb === undefined && planThumb(asset).kind === 'encode'\n}\n\n/** An image record still missing an lqip whose {@link planLqip} decision is `encode`. */\nfunction needsLqip(asset: AssetRecord): boolean {\n return asset.lqip === undefined && planLqip(asset).kind === 'encode'\n}\n\n/**\n * The assets that still need at least one variant (pure, node-tested idempotence\n * core, EC-420 AD-4): an image record missing a needed thumb OR a needed lqip.\n * Records already carrying both, non-images, SVGs, and (for the thumb) already-\n * small images are silently excluded — re-running on a done library is a no-op.\n */\nexport function assetsNeedingVariants(assets: readonly AssetRecord[]): AssetRecord[] {\n return assets.filter((asset) => needsThumb(asset) || needsLqip(asset))\n}\n\n/** The variants an asset is missing — what the per-variant backfill asks the encoder for. */\nexport function variantWantFor(asset: AssetRecord): VariantWant {\n return { thumb: needsThumb(asset), lqip: needsLqip(asset) }\n}\n\n/**\n * The asset write for a backfill result (EC-400 AD-4 / EC-420, EC-577): ONLY the\n * variants just generated. Every other column is absent, so it keeps its stored\n * value — including a variant the record already had (the other half of a\n * per-variant fill) and any metadata an editor saved while the run was going. The\n * restate this replaced wrote the whole listed record back, which overwrote such\n * a concurrent edit with the stale listing — and re-created an asset deleted\n * mid-run; now a write for a vanished asset is refused and counted `failed`.\n */\nexport function assetVariantWrite(assetId: string, variants: GeneratedVariants): AssetWriteInput {\n return {\n id: assetId,\n ...(variants.thumb !== undefined ? { thumb: variants.thumb } : {}),\n ...(variants.lqip !== undefined ? { lqip: variants.lqip } : {}),\n }\n}\n\n/** Live tally the \"Generate previews\" UI renders (EC-400 AD-1). */\nexport interface BackfillProgress {\n /** How many assets need at least one variant (the candidate set size). */\n total: number\n /** How many candidates have been processed (generated + skipped + failed). */\n done: number\n /** How many candidates had at least one variant generated and patched in. */\n generated: number\n /** Candidates the re-plan/encode declined (e.g. undecodable) — silent, valid. */\n skipped: number\n /** Candidates whose fetch/encode/patch errored — surfaced, not fatal. */\n failed: number\n /** Filename of the asset currently in flight (for the progress label). */\n current?: string\n /** Set once the run stops early because the caller cancelled. */\n cancelled?: boolean\n}\n\n/** A mutable cancellation flag the UI flips to stop the sequential run (AD-1). */\nexport interface BackfillSignal {\n cancelled: boolean\n}\n\nexport interface BackfillDeps {\n /** Metadata reads + the variant patch write (the operations facade in the studio). */\n assets: AssetRepository\n /** Blob boundary: fetch each original's bytes, store the thumb variant. */\n blobs: BlobStorageAdapter\n /**\n * Injectable variant producer; defaults to {@link generateVariants} over `blobs`.\n * Receives the per-asset `want` so it produces ONLY the missing variants. Tests\n * pass a deterministic fake so the iterator runs in node.\n */\n generate?: (source: Blob, meta: ThumbSource, want: VariantWant) => Promise<GeneratedVariants>\n /** Fired with each patched record so the caller can update its cache in place. */\n onGenerated?: (asset: AssetRecord) => void\n /** Fired after each candidate (and once at the end) to drive the progress UI. */\n onProgress?: (progress: BackfillProgress) => void\n /** Cooperative cancellation — checked before each candidate (AD-1). */\n signal?: BackfillSignal\n}\n\n/**\n * Run the backfill sequentially over a project's images that still need a variant.\n * Resolves with the final tally; never throws (per-asset failures are counted, not\n * fatal). One fetch per candidate serves both variants; only the missing ones are\n * (re)generated (EC-420 AD-4), so an asset with a thumb but no lqip is patched with\n * just the lqip and its existing thumb blob is left untouched.\n */\nexport async function runVariantBackfill(\n deps: BackfillDeps,\n projectId: string,\n): Promise<BackfillProgress> {\n const all = await deps.assets.listAssets(projectId)\n const candidates = assetsNeedingVariants(all)\n const generate =\n deps.generate ??\n ((source: Blob, meta: ThumbSource, want: VariantWant) =>\n generateVariants({ blobs: deps.blobs }, source, meta, want))\n\n const progress: BackfillProgress = { total: candidates.length, done: 0, generated: 0, skipped: 0, failed: 0 }\n deps.onProgress?.({ ...progress })\n\n for (const asset of candidates) {\n if (deps.signal?.cancelled) {\n progress.cancelled = true\n break\n }\n deps.onProgress?.({ ...progress, current: asset.filename })\n try {\n const bytes = await deps.blobs.get(asset.storageKey)\n if (!bytes) {\n progress.failed += 1\n } else {\n const source = new Blob([bytes as BlobPart], { type: asset.contentType })\n const variants = await generate(\n source,\n {\n contentType: asset.contentType,\n ...(asset.width !== undefined ? { width: asset.width } : {}),\n ...(asset.height !== undefined ? { height: asset.height } : {}),\n },\n variantWantFor(asset),\n )\n if (variants.thumb === undefined && variants.lqip === undefined) {\n progress.skipped += 1\n } else {\n const patched = await deps.assets.upsertAsset(projectId, assetVariantWrite(asset.id, variants))\n deps.onGenerated?.(patched)\n progress.generated += 1\n }\n }\n } catch {\n progress.failed += 1\n }\n progress.done += 1\n deps.onProgress?.({ ...progress })\n }\n\n deps.onProgress?.({ ...progress })\n return progress\n}\n"]}