@murumets-ee/content 0.99.0 → 0.101.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin.mjs +1 -1
- package/dist/chrome-provider.d.mts +1 -1
- package/dist/chrome-provider.mjs +1 -1
- package/dist/client.d.mts +2 -2
- package/dist/client.mjs +1 -1
- package/dist/client.mjs.map +1 -1
- package/dist/context-DtHgyrgb.mjs +2 -0
- package/dist/{context-D7eEItCY.mjs.map → context-DtHgyrgb.mjs.map} +1 -1
- package/dist/document-site-B8tmEqLw.mjs +2 -0
- package/dist/document-site-B8tmEqLw.mjs.map +1 -0
- package/dist/entities/index.d.mts +2 -2
- package/dist/entities/index.mjs +1 -1
- package/dist/{index-C3VyZLjf.d.mts → index-Bni-PiIz.d.mts} +2 -2
- package/dist/{index-C3VyZLjf.d.mts.map → index-Bni-PiIz.d.mts.map} +1 -1
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +1 -1
- package/dist/locale-registry-COsJrVZl.mjs +2 -0
- package/dist/locale-registry-COsJrVZl.mjs.map +1 -0
- package/dist/lock-service.d.mts +1 -1
- package/dist/plugin-CvPWz399.mjs +2 -0
- package/dist/plugin-CvPWz399.mjs.map +1 -0
- package/dist/plugin.d.mts +2 -2
- package/dist/plugin.d.mts.map +1 -1
- package/dist/plugin.mjs +1 -1
- package/dist/resolve.mjs +1 -1
- package/dist/routes-D-NWP0hK.mjs +2 -0
- package/dist/routes-D-NWP0hK.mjs.map +1 -0
- package/dist/{routing-strategy-DV7KGarX.d.mts → routing-strategy-DVWB7qPp.d.mts} +2 -2
- package/dist/{routing-strategy-DV7KGarX.d.mts.map → routing-strategy-DVWB7qPp.d.mts.map} +1 -1
- package/dist/seed.d.mts.map +1 -1
- package/dist/seed.mjs +1 -1
- package/dist/seed.mjs.map +1 -1
- package/dist/site-chrome-BAtQaAqC.mjs +2 -0
- package/dist/{site-chrome-AffFxYrV.mjs.map → site-chrome-BAtQaAqC.mjs.map} +1 -1
- package/dist/{site-chrome-DJ8IJUi1.d.mts → site-chrome-BiV3zhw0.d.mts} +2 -2
- package/dist/{site-chrome-DJ8IJUi1.d.mts.map → site-chrome-BiV3zhw0.d.mts.map} +1 -1
- package/dist/translation-provenance--dHtcmfg.d.mts +253 -0
- package/dist/translation-provenance--dHtcmfg.d.mts.map +1 -0
- package/dist/translation-provenance-eqhsGAyi.mjs +2 -0
- package/dist/translation-provenance-eqhsGAyi.mjs.map +1 -0
- package/dist/translation.d.mts +2 -0
- package/dist/translation.mjs +1 -0
- package/dist/{types-B3K2p9t8.d.mts → types-wMTglM4j.d.mts} +13 -4
- package/dist/types-wMTglM4j.d.mts.map +1 -0
- package/dist/{versionable-ByZgfpp0.d.mts → versionable-D2JjselN.d.mts} +2 -2
- package/dist/{versionable-ByZgfpp0.d.mts.map → versionable-D2JjselN.d.mts.map} +1 -1
- package/dist/{versions-C5_IJpI8.mjs → versions-B0_9TtZ0.mjs} +2 -2
- package/dist/{versions-C5_IJpI8.mjs.map → versions-B0_9TtZ0.mjs.map} +1 -1
- package/package.json +14 -10
- package/dist/context-D7eEItCY.mjs +0 -2
- package/dist/locale-registry-Bn6e_nM7.mjs +0 -2
- package/dist/locale-registry-Bn6e_nM7.mjs.map +0 -1
- package/dist/plugin-DmyWYmuE.mjs +0 -2
- package/dist/plugin-DmyWYmuE.mjs.map +0 -1
- package/dist/registry-CaPbY5lm.mjs +0 -2
- package/dist/registry-CaPbY5lm.mjs.map +0 -1
- package/dist/routes-B6TJ5qiR.mjs +0 -2
- package/dist/routes-B6TJ5qiR.mjs.map +0 -1
- package/dist/site-chrome-AffFxYrV.mjs +0 -2
- package/dist/types-B3K2p9t8.d.mts.map +0 -1
package/dist/admin.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,r as t,t as n}from"./routes-
|
|
1
|
+
import{n as e,r as t,t as n}from"./routes-D-NWP0hK.mjs";export{e as PATH_RESOLVE_PERMISSION,t as pathRoutes,n as redirectRoutes};
|
package/dist/chrome-provider.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./chrome-entity-names-zYJzP-_U.mjs";import{t}from"./site-chrome-
|
|
1
|
+
import{t as e}from"./chrome-entity-names-zYJzP-_U.mjs";import{t}from"./site-chrome-BAtQaAqC.mjs";import{getBlockTreeFieldName as n}from"@murumets-ee/entity";import{composeChromeRegion as r,stripScopeTags as i}from"@murumets-ee/blocks/render";const a=t;async function o(e,t){let n=e.document&&(!t.claim||t.claim())?await t.readOverrides(e.document.entityType,e.document.id,e.locale):null,o={header:null,footer:null};for(let s of a){if(t.claim&&!t.claim())continue;let a=await t.readChromeDocument(s,e.locale);if(!a)continue;let c={id:a.id,blocks:a.blocks};try{let e=r(c,n);if(!e)continue;o[s]={blocks:i(e.blocks),overridden:e.overridden}}catch(n){t.logger?.warn({region:s,documentId:c.id,locale:e.locale,err:n},`content: chrome region failed to compose (malformed stored blocks, or strip depth exceeded) — serving no chrome for this region`)}}return a.some(e=>o[e]!==null)?o:null}function s(t){return{entity:e,getChrome:async r=>{let i=await t(),{createQueryClient:a}=await import(`@murumets-ee/core/clients`),{schemaRegistry:s}=await import(`@murumets-ee/db`),{eq:c,getTableColumns:l}=await import(`drizzle-orm`),u=e=>{let t=s.get(e);if(t)return l(t)},d=async(e,t,n,r)=>{let o=i.entities.get(e);return o?(await a(o).findMany({limit:1,locale:t,...n!==void 0&&{where:n},...r!==void 0&&{exposeInternalFields:r}}))[0]??null:null},f=i.entities.get(e),p=f?n(f):void 0,m=u(e)?.placement;return!p||!m?null:o(r,{claim:()=>r.budget.claim(`block`,1)>0,readChromeDocument:async(t,n)=>{let r=await d(e,n,c(m,t));if(!r)return null;let i=r[p];return{id:typeof r.id==`string`?r.id:e,blocks:Array.isArray(i)?i:[]}},readOverrides:async(e,t,n)=>{let r=u(e)?.id;if(!r)return null;let i=await d(e,n,c(r,t),[`_overrides`]);if(!i)return null;let a=i._overrides;return a&&typeof a==`object`&&!Array.isArray(a)?a:null},logger:i.logger})}}}export{o as composeChromeRegions,s as createChromeProvider};
|
|
2
2
|
//# sourceMappingURL=chrome-provider.mjs.map
|
package/dist/client.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { d as TranslationReport, f as TranslationStatus, n as DraftEntry, p as VersionEntry, s as LocalePublishStatus } from "./types-
|
|
2
|
-
import { h as FieldDiff } from "./index-
|
|
1
|
+
import { d as TranslationReport, f as TranslationStatus, n as DraftEntry, p as VersionEntry, s as LocalePublishStatus } from "./types-wMTglM4j.mjs";
|
|
2
|
+
import { h as FieldDiff } from "./index-Bni-PiIz.mjs";
|
|
3
3
|
import { Entity, FieldConfig } from "@murumets-ee/entity";
|
|
4
4
|
import { Logger } from "@murumets-ee/core";
|
|
5
5
|
import { AdminClient, FindManyOptions, InferCreateInput, InferEntityDTO, InferUpdateInput } from "@murumets-ee/entity/admin";
|
package/dist/client.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./versionable-Br_G5VGR.mjs";import{n as t,r as n,t as r}from"./errors-NRNILhhm.mjs";import{t as i}from"./content-config-store-8omQF5p5.mjs";import{a,d as o,f as s,h as c,i as l,l as u,m as d,n as f,o as p,p as m,r as h,s as g,t as _,u as
|
|
1
|
+
import{t as e}from"./versionable-Br_G5VGR.mjs";import{n as t,r as n,t as r}from"./errors-NRNILhhm.mjs";import{t as i}from"./content-config-store-8omQF5p5.mjs";import{a,d as o,f as s,h as c,i as l,l as u,m as d,n as f,o as p,p as m,r as h,s as g,t as _,u as v}from"./versions-B0_9TtZ0.mjs";import{c as y,f as b,r as x}from"./translation-provenance-eqhsGAyi.mjs";import{n as S}from"./plugin-CvPWz399.mjs";import{t as C}from"./locale-utils-B0mFoV47.mjs";import{i as w,n as T,r as E}from"./context-DtHgyrgb.mjs";import{blockTreeFieldsOf as D,buildPartitionCondition as O}from"@murumets-ee/entity";import{getApp as k,getContext as A,requireSiteFor as ee}from"@murumets-ee/core";import{schemaRegistry as te}from"@murumets-ee/db";import{and as ne,inArray as j}from"drizzle-orm";import"server-only";import{createAdminClient as M}from"@murumets-ee/core/clients";function N(e){return{id:e.id,entityId:e.entityId,locale:e.locale,data:e.data,createdBy:e.createdBy,createdByName:e.createdByName??null,createdAt:e.createdAt,updatedAt:e.updatedAt}}async function P(e,t,n){try{return await e.admin.findById(t,n===`_`?{}:{locale:n})??void 0}catch(n){e.logger?.warn({entity:e.entity.name,entityId:t,error:n},`draft: the live row could not be read to grandfather its block tree`);return}}async function F(e,t,n,r,i){let a=typeof i==`object`&&i?i:void 0;if(!D(e.entity).some(({name:e})=>Object.hasOwn(r,e)&&!Array.isArray(a?.[e])))return a;let o=await P(e,t,n);return o===void 0?a:{...o,...a}}async function I(e,n,r,i=`_`,a){C(i);let s=await E(e);if(!s)throw new t(e.entity.name,`drafts`);let c=o(e.entity,r);e.admin.assertBlockTreesValid(c);let l=D(e.entity).some(({name:e})=>Object.hasOwn(c,e))?await s.findOne({entityId:n,locale:i}):null;await e.admin.assertBlockTreesFitDocument(c,()=>F(e,n,i,c,l?.data),{loadAreaRow:()=>P(e,n,i)}),await e.admin.assertMediaKindsValid(c,l?.data);let u=new Date,d=a?.id??``,f=a?.name??null,p=await s.upsert({entityId:n,locale:i,data:c,createdBy:d,createdByName:f,createdAt:u,updatedAt:u},{target:[`entityId`,`locale`],set:{data:c,updatedAt:u}});return await y({entityName:e.entity.name,entityId:n,locale:i,userId:a?.id,draftData:p.data??{}}),N(p)}const L=[`slug`,`slugMode`,`parent`];async function R(e,n,r,i=`_`,a){C(i);let s=await E(e);if(!s)throw new t(e.entity.name,`drafts`);let c=o(e.entity,r);if(Object.keys(c).length===0){let e=await s.findOne({entityId:n,locale:i});return e?N(e):null}e.admin.assertBlockTreesValid(c),e.admin.assertUpdateValid(c);let l=D(e.entity).some(({name:e})=>Object.hasOwn(c,e)),u=e.entity.frontend?.path!==void 0&&L.some(e=>Object.hasOwn(c,e)),d=l||u?await s.findOne({entityId:n,locale:i}):null;if(await e.admin.assertBlockTreesFitDocument(c,()=>F(e,n,i,c,d?.data),{loadAreaRow:()=>P(e,n,i)}),await e.admin.assertMediaKindsValid(c,d?.data),u){let t={...d?.data??{},...c};if(i===`_`)await e.admin.assertPathAvailable(n,t);else{let r=e.entity.allFields,a={},o={};for(let[e,n]of Object.entries(t))r[e]?.translatable===!0?a[e]=n:o[e]=n;let s=e=>L.some(t=>Object.hasOwn(e,t)&&Object.hasOwn(c,t));s(a)&&await e.admin.assertPathAvailable(n,a,i),s(o)&&await e.admin.assertPathAvailable(n,o)}}let f=new Date,p=await s.upsert({entityId:n,locale:i,data:c,createdBy:a?.id??``,createdByName:a?.name??null,createdAt:f,updatedAt:f},{target:[`entityId`,`locale`],set:{updatedAt:f},mergeJsonb:[`data`]});return await y({entityName:e.entity.name,entityId:n,locale:i,userId:a?.id,draftData:p.data??{}}),N(p)}async function z(e,t,n=`_`){C(n);let r=await E(e);if(!r)return null;let i=await r.findOne({entityId:t,locale:n});return i?N(i):null}async function B(e,t,n=`_`){C(n);let r=await E(e);if(!r)return!1;let i=await r.deleteMany({entityId:t,locale:n});return i.length>0&&await y({entityName:e.entity.name,entityId:t,locale:n,reverted:!0}),i.length>0}async function V(e,n,i=`_`,a){if(C(i),!await E(e))throw new t(e.entity.name,`drafts`);let c=e.versionableOptions?await e.admin.findById(n,m(i)):null;return e.db.transaction(async l=>{let u={...e,db:l},d=await E(u);if(!d)throw new t(e.entity.name,`drafts`);let[p]=await d.deleteMany({entityId:n,locale:i});if(!p)throw new r(n,i);let{publishedAt:m,...h}=p.data??{},g=await s(u,n,o(e.entity,{...h,status:`published`}),i,l),_=H(e.entity,h);return _!==void 0&&await e.admin.updateInternal(n,{_overrides:_},{tx:l}),e.versionableOptions&&await f(u,n,g,c,i,a),g})}function H(e,t){if(!(e.behaviors??[]).some(e=>e.name===`withOverrides`))return;let n=e.allFields._overrides;if(n===void 0||n.internal!==!0)return;let r=t._overrides;if(!(typeof r!=`object`||!r||Array.isArray(r)))return r}async function U(e,t,n=`_`){C(n);let r=await E(e);return r?r.exists({entityId:t,locale:n}):!1}async function W(e,t=`_`){C(t);let n=await E(e);return n?n.count({locale:t}):0}async function G(e,t,n=`_`){C(n);let r=new Set;if(t.length===0)return r;let i=await E(e);if(!i)return r;let a=await i.findMany({where:{entityId:{in:t},locale:n}});for(let e of a)r.add(e.entityId);return r}async function K(e,t,n=`_`){C(n);let r=await z(e,t,n);if(!r)return null;let a=i().defaultLocale,o=n===`_`?{defaultLocale:a}:{locale:n,defaultLocale:a},s=await e.admin.findById(t,o);if(!s)return null;let l=e.entity.allFields,u=s,f=r.data,p={};for(let e of Object.keys(f))p[e]=u[e];let m=c(p,f,l);for(let e of m)e.type===`blockTree`&&(e.blockDiffs=d(Array.isArray(e.from)?e.from:[],Array.isArray(e.to)?e.to:[]));return{diffs:m,current:s,draft:r}}async function q(e,t){let n=(await Y(e,[t])).get(t);return n?Object.values(n):[]}async function J(e,n,r,a){C(r);let o=i();if(r===o.defaultLocale){let t={status:a};a===`published`&&(t.publishedAt=new Date),await e.admin.update(n,t);return}let s=await w(e);if(!s)throw new t(e.entity.name,`localeStatus`);let c={status:a};await e.admin.updateForLocale(n,c,r,{defaultLocale:o.defaultLocale,localeStatusWriter:(e,t,n)=>S(s,e,t,n)})}async function Y(e,t){let n=new Map;if(t.length===0)return n;let r=await w(e);if(!r)return n;let i=await r.findMany({where:{entityId:{in:t}}});for(let e of i){let t=e.entityId,r=e.locale,i=n.get(t);i||(i={},n.set(t,i)),i[r]={locale:r,status:e.status,publishedAt:e.publishedAt??null}}return n}function X(){let e=i(),t=A();return{locales:(t?.availableLocales??e.locales.map(e=>e.code)).map(e=>({code:e})),defaultLocale:t?.defaultLocale??e.defaultLocale}}function re(e,t,n,r){let i={};for(let a of n){if(a.code===r)continue;let n=t?.get(a.code)??{},o=[];for(let t of e)(n[t]===void 0||n[t]===null)&&o.push(t);i[a.code]={complete:o.length===0,total:e.length,translated:e.length-o.length,missing:o}}return i}async function ie(e,t){return(await Z(e,[t])).get(t)??{}}async function Z(e,t){let n=new Map;if(t.length===0)return n;let{locales:r,defaultLocale:i}=X(),a=Object.entries(e.entity.allFields).filter(([e,t])=>t.translatable).map(([e])=>e);if(a.length===0)return n;let o=te.get(`${e.entity.name}_translations`);if(!o)return n;let s=await ee(e.entity),c=j(o.entityId,t),l=await e.db.select().from(o).where(s===void 0?c:ne(c,O(o,{site:s},e.entity.name))),u=new Map;for(let e of l){let t=e,n=t.entityId,r=t.locale,i={};for(let e of a)i[e]=t[e];let o=u.get(n);o||(o=new Map,u.set(n,o)),o.set(r,i)}let d=await x(e.entity.name,t,e.db);for(let e of t){let t=re(a,u.get(e),r,i),o=d.get(e);for(let[e,n]of Object.entries(t)){let t=b(o,e);t&&(n.freshness=t)}n.set(e,t)}return n}const Q={total:0,complete:0,partial:0,missing:0,outdated:0,machineUnreviewed:0};async function ae(e,t){let{locales:r,defaultLocale:i}=X(),a=t?.locale??r.find(e=>e.code!==i)?.code;if(!a)return{...Q};if(!r.some(e=>e.code===a))throw new n(a,r.map(e=>e.code));let o=await e.admin.findMany();if(o.length===0)return{...Q};let s=await Z(e,o.map(e=>e.id)),c=0,l=0,u=0,d=0,f=0;for(let e of o){let t=s.get(e.id)?.[a];!t||t.translated===0?u++:t.complete?c++:l++,t?.freshness?.outdated===!0&&d++,t?.freshness?.machineUnreviewed===!0&&f++}return{total:o.length,complete:c,partial:l,missing:u,outdated:d,machineUnreviewed:f}}var $=class{ctx;constructor(t){let n=e(t.entity.behaviors);this.ctx=T(t,n)}async create(e){let t=await this.ctx.admin.create(e);return this.ctx.versionableOptions&&await g(this.ctx,t.id,t,null,!1),t}findById(e,t){return this.ctx.admin.findById(e,t)}findMany(e){return this.ctx.admin.findMany(e)}async update(e,t){let n=null;this.ctx.versionableOptions&&(n=await this.ctx.admin.findById(e));let r=await this.ctx.admin.update(e,t);if(this.ctx.versionableOptions&&n){let t=v(n,r),i=await g(this.ctx,e,r,t,!1);if(i!==void 0)return await u(this.ctx,e,i),await a(this.ctx,e),{...r,_version:i};await a(this.ctx,e)}return r}delete(e){return this.ctx.admin.delete(e)}saveTranslation(e,t,n){return this.ctx.admin.saveTranslation(e,t,n)}deleteTranslation(e,t){return this.ctx.admin.deleteTranslation(e,t)}getVersions(e,t){return l(this.ctx,e,t)}getVersion(e,t,n){return h(this.ctx,e,t,n)}compareVersions(e,t,n,r){return _(this.ctx,e,t,n,r)}restoreVersion(e,t,n){return p(this.ctx,e,t,n)}pruneVersions(e,t){return a(this.ctx,e,t)}createVersionSnapshot(e,t,n,r,i){return f(this.ctx,e,t,n,r,i)}getTranslationStatus(e){return ie(this.ctx,e)}getTranslationStatusBatch(e){return Z(this.ctx,e)}getTranslationReport(e){return ae(this.ctx,e)}getLocaleStatus(e){return q(this.ctx,e)}setLocaleStatus(e,t,n){return J(this.ctx,e,t,n)}getLocaleStatusBatch(e){return Y(this.ctx,e)}saveDraft(e,t,n,r){return I(this.ctx,e,t,n,r)}mergeDraft(e,t,n,r){return R(this.ctx,e,t,n,r)}getDraft(e,t){return z(this.ctx,e,t)}deleteDraft(e,t){return B(this.ctx,e,t)}publishDraft(e,t,n){return V(this.ctx,e,t,n)}hasDraft(e,t){return U(this.ctx,e,t)}countDrafts(e){return W(this.ctx,e)}hasDraftBatch(e,t){return G(this.ctx,e,t)}compareDraftWithCurrent(e,t){return K(this.ctx,e,t)}};function oe(e){return new $({admin:M(e),entity:e,logger:k().logger.child({content:e.name})})}export{$ as ContentClient,oe as createContentClient};
|
|
2
2
|
//# sourceMappingURL=client.mjs.map
|
package/dist/client.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.mjs","names":[],"sources":["../src/drafts.ts","../src/locale-status.ts","../src/translation-status.ts","../src/client.ts"],"sourcesContent":["/**\n * Draft-overlay operations.\n *\n * Capability: requires the entity to declare `publishable()`. Reads\n * (`getDraft`, `hasDraft`, `countDrafts`, `hasDraftBatch`) silently\n * return falsy when the entity doesn't support drafts; writes\n * (`saveDraft`, `mergeDraft`, `publishDraft`) throw `EntityCapabilityError`.\n */\n\nimport 'server-only'\n\nimport { blockTreeFieldsOf, type FieldConfig } from '@murumets-ee/entity'\nimport type { InferEntityDTO, InferUpdateInput } from '@murumets-ee/entity/admin'\nimport { diffBlocks } from './diff/block-diff.js'\nimport { diffFields } from './diff/field-diff.js'\nimport type { FieldDiff } from './diff/types.js'\nimport { DraftNotFoundError, EntityCapabilityError } from './errors.js'\nimport {\n applyLocaleRoutedUpdate,\n localeFindOptions,\n} from './internal/apply-locale-routed-update.js'\nimport { type ContentContext, getDraftsClient } from './internal/context.js'\nimport { projectToEntityFields } from './internal/projection.js'\nimport { DEFAULT_LOCALE_SENTINEL, validateLocale } from './locale-utils.js'\nimport { getContentConfig } from './plugin.js'\nimport type { DraftsTable } from './schema/drafts.js'\nimport type { DraftEntry } from './types.js'\nimport { createVersionSnapshot } from './versions.js'\n\ntype DraftRow = NonNullable<Awaited<ReturnType<ReturnType<DraftsTable['makeClient']>['findOne']>>>\n\nfunction toDraftEntry(row: DraftRow): DraftEntry {\n return {\n id: row.id,\n entityId: row.entityId,\n locale: row.locale,\n data: row.data,\n createdBy: row.createdBy,\n createdByName: row.createdByName ?? null,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n }\n}\n\n/**\n * The live row behind a draft, in the draft's locale — `undefined` when it\n * cannot be read. Never throws: the caller treats an unreadable row as \"no\n * stored copy\", which is the strict answer.\n */\nasync function liveRow<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale: string,\n): Promise<Record<string, unknown> | undefined> {\n try {\n const row = await ctx.admin.findById(\n entityId,\n locale === DEFAULT_LOCALE_SENTINEL ? {} : { locale },\n )\n return (row as Record<string, unknown> | null) ?? undefined\n } catch (error) {\n ctx.logger?.warn(\n { entity: ctx.entity.name, entityId, error },\n 'draft: the live row could not be read to grandfather its block tree',\n )\n return undefined\n }\n}\n\n/**\n * What a draft save's block trees are judged AGAINST: the stored draft's tree\n * for a field the draft already holds, the live row's for one it does not.\n * The live row is read only in the second case.\n */\nasync function storedTreesFor<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale: string,\n projected: Record<string, unknown>,\n draftData: unknown,\n): Promise<Record<string, unknown> | undefined> {\n const draft =\n draftData !== null && typeof draftData === 'object'\n ? (draftData as Record<string, unknown>)\n : undefined\n const missing = blockTreeFieldsOf(ctx.entity).some(\n ({ name }) => Object.hasOwn(projected, name) && !Array.isArray(draft?.[name]),\n )\n if (!missing) return draft\n const live = await liveRow(ctx, entityId, locale)\n if (live === undefined) return draft\n return { ...live, ...draft }\n}\n\n/**\n * Save (upsert) a draft for an entity+locale. One draft per\n * entity+locale — overwrites any existing draft.\n *\n * `data` is projected through the entity's declared field whitelist\n * BEFORE it is stored (same `projectToEntityFields` call `publishDraft`\n * makes on the way out). Storing the caller's JSON verbatim let a draft\n * carry keys the entity never declared, identity/audit columns and\n * `internal: true` fields; publishing filtered them, but `getDraft` and\n * `compareDraftWithCurrent` echoed them straight back to the admin UI,\n * and the drafts table accumulated arbitrary caller-controlled JSON\n * (`plan/admin-api-hardening` F002). Validating at the write closes the\n * asymmetry — the stored draft is now always a subset of what the entity\n * can actually hold.\n */\nexport async function saveDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n data: InferUpdateInput<F>,\n locale = DEFAULT_LOCALE_SENTINEL,\n user?: { id: string; name?: string },\n): Promise<DraftEntry<InferUpdateInput<F>>> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n\n const projected = projectToEntityFields(ctx.entity, data as Record<string, unknown>)\n\n // `projectToEntityFields` is a field-NAME whitelist — it never inspects a\n // value, so a `field.blockTree()` column in a draft took arbitrary JSON, and\n // `editor-state` hands the stored draft back as the CANVAS BASE STATE\n // (editor F002). Publishing is already gated by the entity write path, but\n // waiting until publish means the editor loads a tree it cannot represent.\n // Same validator, same judgement — asked here because the draft blob carries\n // no Zod schema of its own.\n ctx.admin.assertBlockTreesValid(projected)\n // …and the STRICT judgement for a token-derived caller (agent-access D014):\n // a draft is published later by whoever presses Publish, so a tree a machine\n // could not store directly must not be parked here for a person to promote.\n // F116, same reasoning — and this is precisely the write path the finding\n // was filed against: dava's home-page DRAFT already holds a mismatched\n // media reference. Grandfathering against the draft ALREADY STORED (rather\n // than validating strictly) is what keeps that draft's next autosave\n // working instead of turning \"a broken image\" into \"a draft that can never\n // be saved again\".\n //\n // The lookup is skipped entirely when the PROJECTED payload carries no\n // block-tree field at all — `assertMediaKindsValid` would no-op anyway\n // (same optimization as `saveTranslation`'s), and most entities with\n // drafts have no block-tree field to begin with.\n const hasBlockTreeValue = blockTreeFieldsOf(ctx.entity).some(({ name }) =>\n Object.hasOwn(projected, name),\n )\n const existing = hasBlockTreeValue ? await client.findOne({ entityId, locale }) : null\n // Grandfathered against the draft already stored, like the media-kind check\n // below: a tree that was there before this save is not what this save adds.\n // With no draft yet, against the live row — a first draft of a document\n // whose live tree holds a block no longer placeable there must still save\n // (davatoidud-toolkit D006).\n await ctx.admin.assertBlockTreesFitDocument(\n projected,\n () => storedTreesFor(ctx, entityId, locale, projected, existing?.data),\n { loadAreaRow: () => liveRow(ctx, entityId, locale) },\n )\n await ctx.admin.assertMediaKindsValid(\n projected,\n existing?.data as Record<string, unknown> | undefined,\n )\n\n const now = new Date()\n const createdBy = user?.id ?? ''\n const createdByName = user?.name ?? null\n\n const row = await client.upsert(\n {\n entityId,\n locale,\n data: projected,\n createdBy,\n createdByName,\n createdAt: now,\n updatedAt: now,\n },\n {\n target: ['entityId', 'locale'],\n // On conflict, only update the mutable fields — preserve createdBy/createdAt.\n set: { data: projected, updatedAt: now },\n },\n )\n\n return toDraftEntry(row) as DraftEntry<InferUpdateInput<F>>\n}\n\n/**\n * The keys that move a document's canonical URL in the patterns the toolkit\n * ships (`[slug]`, `[parent.path]`) plus the slug mode that decides whether a\n * clash is refused or auto-suffixed. A merge naming one of them, on a ROUTABLE\n * entity, runs the path-conflict check (see `mergeDraft`); any other merge\n * skips its lookups — the staged draft, the row, and `toolkit_paths` (twice\n * under a parent).\n *\n * A pattern built from another field (`/[category]/[slug]`) is not covered:\n * staging only `category` is refused at Publish rather than here.\n */\nconst PATH_KEYS = ['slug', 'slugMode', 'parent'] as const\n\n/**\n * Stage a PARTIAL change: merge `patch` into the entity+locale draft, creating\n * the draft if there is none. Keys not in `patch` are left exactly as the draft\n * (or, absent a draft key, the live row) has them.\n *\n * This is the write every editing surface uses since editor D019 — \"every edit\n * on every surface saves to the document's one shared draft\". `saveDraft`\n * REPLACES the blob, which is right for a surface that owns the whole document\n * (the menu editor) and wrong for one that owns a few fields of it: page\n * settings saving `title` through `saveDraft` would erase the block edits the\n * canvas staged a second earlier. A draft is therefore a patch over the row, and\n * every reader that shows editable values reads row ⊕ draft.\n *\n * Judged like the entity PATCH it replaces, BEFORE it is stored:\n * - projected through the field whitelist (`internal`, undeclared keys dropped)\n * - `assertBlockTreesValid` + `assertMediaKindsValid` (grandfathered against the\n * stored draft, same as `saveDraft`)\n * - `assertUpdateValid` — the entity's own update schema. `saveDraft` never ran\n * it, which was harmless while the form's Publish still PATCHed; moving a\n * surface into the draft must not move its refusal to Publish, where the\n * author is no longer looking at the field.\n * - `assertPathAvailable` — the path-conflict guard, as a dry run, when the\n * merge moves the URL (see {@link PATH_KEYS}) on a routable entity (F150).\n *\n * 🔴 ONE STATEMENT, not read-modify-write. The merge is `data || patch` inside\n * `ON CONFLICT DO UPDATE` (`TableClient.upsert`'s `mergeJsonb`), so it cannot\n * lose a concurrent write: a read-then-upsert that interleaved with op-commit's\n * or a bound field's stage would write back the draft as it was read — silently\n * reverting the other writer's change. `writeDraft` merges the same way, so\n * neither can erase the other. Top-level `||`, a SHALLOW merge.\n *\n * Resolves `null` when the projected patch is EMPTY and no draft exists: nothing\n * the entity declares was sent, so nothing is staged and no empty draft row is\n * created.\n *\n * ⚠️ The rest of the write path's hooks — `pathParent()`'s cycle check, the\n * partial-unique slug index, `sluggable()`'s regeneration — still run only at\n * Publish, inside its transaction, where a refusal stops the whole publish. The\n * path check here answers \"as of now\"; Publish runs the real guard again.\n */\nexport async function mergeDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n patch: InferUpdateInput<F>,\n locale = DEFAULT_LOCALE_SENTINEL,\n user?: { id: string; name?: string },\n): Promise<DraftEntry<InferUpdateInput<F>> | null> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n\n const projected = projectToEntityFields(ctx.entity, patch as Record<string, unknown>)\n // Nothing the entity declares: stage nothing. Upserting `{}` would CREATE an\n // empty draft, and the document would then read \"Draft saved · not live\n // yet\" about a change that does not exist.\n if (Object.keys(projected).length === 0) {\n const current = await client.findOne({ entityId, locale })\n return current ? (toDraftEntry(current) as DraftEntry<InferUpdateInput<F>>) : null\n }\n ctx.admin.assertBlockTreesValid(projected)\n ctx.admin.assertUpdateValid(projected)\n const hasBlockTreeValue = blockTreeFieldsOf(ctx.entity).some(({ name }) =>\n Object.hasOwn(projected, name),\n )\n const touchesPath =\n ctx.entity.frontend?.path !== undefined &&\n PATH_KEYS.some((key) => Object.hasOwn(projected, key))\n const existing =\n hasBlockTreeValue || touchesPath ? await client.findOne({ entityId, locale }) : null\n // The contextual judgement — the document's area for everyone, the strict\n // tree for a token-derived caller (agent-access D014) — with the stored\n // draft, or the live row when there is none, to grandfather against. See\n // `saveDraft`.\n await ctx.admin.assertBlockTreesFitDocument(\n projected,\n () => storedTreesFor(ctx, entityId, locale, projected, existing?.data),\n { loadAreaRow: () => liveRow(ctx, entityId, locale) },\n )\n await ctx.admin.assertMediaKindsValid(\n projected,\n existing?.data as Record<string, unknown> | undefined,\n )\n // A staged slug that another document's URL already holds is refused NOW,\n // beside the field the author typed it in — not first at Publish (editor\n // PR60, F150). Checked against what the draft will hold after this merge,\n // since an earlier stage may have set `slugMode` or `parent`.\n if (touchesPath) {\n const staged = {\n ...((existing?.data as Record<string, unknown> | undefined) ?? {}),\n ...projected,\n }\n if (locale === DEFAULT_LOCALE_SENTINEL) {\n await ctx.admin.assertPathAvailable(entityId, staged)\n } else {\n // Checked the way Publish writes it: `updateForLocale` sends a locale's\n // TRANSLATABLE fields through that locale's guard and the rest (a\n // `parent`, a non-translatable slug) through `update()`, whose guard\n // checks the default locale. One guard over everything would test a\n // shared `parent` against the wrong locale's URLs.\n const fields = ctx.entity.allFields as Record<string, { translatable?: boolean } | undefined>\n const translatable: Record<string, unknown> = {}\n const shared: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(staged)) {\n if (fields[key]?.translatable === true) translatable[key] = value\n else shared[key] = value\n }\n const moves = (part: Record<string, unknown>) =>\n PATH_KEYS.some((key) => Object.hasOwn(part, key) && Object.hasOwn(projected, key))\n if (moves(translatable)) await ctx.admin.assertPathAvailable(entityId, translatable, locale)\n if (moves(shared)) await ctx.admin.assertPathAvailable(entityId, shared)\n }\n }\n\n const now = new Date()\n const row = await client.upsert(\n {\n entityId,\n locale,\n data: projected,\n createdBy: user?.id ?? '',\n createdByName: user?.name ?? null,\n createdAt: now,\n updatedAt: now,\n },\n { target: ['entityId', 'locale'], set: { updatedAt: now }, mergeJsonb: ['data'] },\n )\n return toDraftEntry(row) as DraftEntry<InferUpdateInput<F>>\n}\n\n/**\n * Get the draft for an entity+locale, or null if none exists (or the\n * entity doesn't support drafts).\n */\nexport async function getDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<DraftEntry<InferUpdateInput<F>> | null> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) return null\n const row = await client.findOne({ entityId, locale })\n return row ? (toDraftEntry(row) as DraftEntry<InferUpdateInput<F>>) : null\n}\n\n/**\n * Delete (discard) a draft for an entity+locale. Returns whether\n * anything was deleted; safely no-ops on entities without drafts.\n */\nexport async function deleteDraft(\n ctx: ContentContext,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<boolean> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) return false\n const deleted = await client.deleteMany({ entityId, locale })\n return deleted.length > 0\n}\n\n/**\n * Publish a draft: make THIS document's staged changes live.\n *\n * \"Publish\" means one thing on every surface (editor D019): the draft's fields\n * are written to the row for the draft's locale AND the row is put live. The\n * draft is then gone and, if versionable, a version snapshot records what went\n * live.\n *\n * Locale routing mirrors the admin PATCH handler (and the taxonomy fix\n * in 10a7cc2b): a default-locale draft writes the base row; a\n * non-default-locale draft routes translatable fields to\n * `saveTranslation` (→ `{entity}_translations`), `status` to the\n * per-locale status table, and only non-translatable fields (which have\n * no per-locale home) to the base row. Without this split, publishing\n * an `et` draft overwrote the default-locale base row wholesale.\n *\n * ## ONE TRANSACTION (editor PR60, R055 §4)\n *\n * The row write, the locale status, `_overrides`, the draft delete and the\n * version snapshot commit together or not at all. They used to be five separate\n * statements, so a failure part-way left a document whose content was live and\n * whose draft still claimed to be pending — or, worse, whose draft was gone while\n * the row write had not landed.\n *\n * The draft is CLAIMED first, by deleting it and publishing what the delete\n * returned. The delete takes the row lock, so an op-commit that is mid-flight on\n * the same draft either committed before (and its edit is in what we publish) or\n * blocks until we commit and then retries its SERIALIZABLE transaction — or, if it\n * had not read the draft yet, inserts a fresh draft holding only its own patch.\n * Either way it does not write a stale copy back over the published one. The editor also flushes and awaits its own in-flight saves\n * before it calls this, so the lock is the backstop, not the mechanism.\n *\n * Path-index and write notifications fire after COMMIT, not inside it —\n * `AdminClient.afterCommit` defers them on a tracked transaction.\n */\nexport async function publishDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n user?: { id: string; name?: string },\n): Promise<InferEntityDTO<F>> {\n validateLocale(locale)\n if (!(await getDraftsClient(ctx))) {\n throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n }\n\n // Previous state for the version delta — locale-merged, so the delta compares\n // against what this locale's readers actually saw. Read BEFORE the\n // transaction: it is the committed state the publish replaces.\n const previousState: InferEntityDTO<F> | null = ctx.versionableOptions\n ? await ctx.admin.findById(entityId, localeFindOptions(locale))\n : null\n\n return ctx.db.transaction(async (tx) => {\n // Every table client below binds to `tx` through this context — drafts,\n // locale status, versions and the `_version` column write.\n const txCtx: ContentContext<F> = { ...ctx, db: tx }\n const draftsClient = await getDraftsClient(txCtx)\n if (!draftsClient) throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n const [claimed] = await draftsClient.deleteMany({ entityId, locale })\n if (!claimed) {\n throw new DraftNotFoundError(entityId, locale)\n }\n\n // `?? {}` because the column is `jsonb NOT NULL`, and that forbids SQL NULL\n // while permitting the JSON literal `null` — which deserializes to JS `null`.\n // A bare cast then made `draftData.status` a TypeError, so a malformed row\n // 500'd the publish route instead of taking the ordinary \"nothing declared,\n // publish the row as-is\" path below. Nothing in this package writes such a\n // row; a seed, a migration or a hand-edit can.\n const claimedData = (claimed.data ?? {}) as Record<string, unknown>\n // `publishedAt` is Publish's to set, like `status` below: a staged value\n // would let whoever wrote the draft back- or forward-date the publication.\n // publishable()'s hook fills it when the UPDATE carries none — which, with\n // the staged value dropped, is every publish: it records the LATEST\n // publication, not the first.\n const { publishedAt: _stagedPublishedAt, ...draftData } = claimedData\n // \"Publish\" means MAKE LIVE, always — the status is not the draft's to\n // decide. Block-editor drafts carry no `status` at all, and before D019 a\n // form-saved draft could carry `status: 'draft'`, which then won: Publish\n // wrote the content and left the document unpublished, so the same button\n // meant \"publish\" on one surface and \"stage\" on another. The publishable()\n // behavior auto-sets `publishedAt` on the transition. The publish-permission\n // gate lives in the admin route, not here.\n const updateData = projectToEntityFields(ctx.entity, { ...draftData, status: 'published' })\n const result = await applyLocaleRoutedUpdate(txCtx, entityId, updateData, locale, tx)\n\n // F009 — promote the page's chrome overrides.\n //\n // `projectToEntityFields` drops every `internal: true` field, deliberately, so\n // `_overrides` cannot ride the generic promotion. That guard is NOT relaxed:\n // this is one named field, written through the trusted `updateInternal` path\n // that `with-overrides.ts` documents as \"the only path that can mutate it\".\n // Before F009 that call site did not exist, so an override survived in the\n // draft buffer and never reached the column — the op committed, the canvas\n // updated, and a reload brought the hidden header back.\n //\n // AFTER the main update, so the override never lands against content that\n // failed to — and inside the same transaction, so neither lands alone.\n // `_overrides` is not translatable, so it belongs on the base row for every\n // locale.\n const overrides = readOverridesForPublish(ctx.entity, draftData)\n if (overrides !== undefined) {\n await ctx.admin.updateInternal(entityId, { _overrides: overrides }, { tx })\n }\n\n if (ctx.versionableOptions) {\n await createVersionSnapshot(txCtx, entityId, result, previousState, locale, user)\n }\n\n return result\n })\n}\n\n/**\n * The page's override map from a draft payload, when the entity declares the\n * field and the draft carries one.\n *\n * Returns `undefined` — never `{}` — so an ordinary content publish does not\n * touch the column. Shape-guarded because a draft payload is stored jsonb: an\n * array or a scalar is malformed data, not an override map. ← F009\n */\nfunction readOverridesForPublish(\n entity: { allFields: Record<string, unknown>; behaviors?: readonly { name: string }[] },\n draftData: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n // The BEHAVIOR, not just a field with the right name — a draft payload is\n // stored jsonb and can be crafted or legacy, so this must not become a way\n // to promote arbitrary JSON into an unrelated internal field on an entity\n // that never opted in. Requiring the behavior also means `beforeUpdate` runs\n // `validateOverridesMap` on the way through `updateInternal`.\n if (!(entity.behaviors ?? []).some((b) => b.name === 'withOverrides')) return undefined\n const field = entity.allFields._overrides as { internal?: boolean } | undefined\n if (field === undefined || field.internal !== true) return undefined\n const value = draftData._overrides\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n return value as Record<string, unknown>\n}\n\n/**\n * Quick existence check for list badges — does a draft exist?\n */\nexport async function hasDraft(\n ctx: ContentContext,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<boolean> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) return false\n return client.exists({ entityId, locale })\n}\n\n/**\n * Count drafts for this entity type, optionally filtered by locale.\n * Single indexed COUNT — used by dashboard widgets.\n */\nexport async function countDrafts(\n ctx: ContentContext,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<number> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) return 0\n return client.count({ locale })\n}\n\n/**\n * Check draft existence for multiple entities in one query. Returns\n * a set of entity IDs that have a draft for `locale`.\n */\nexport async function hasDraftBatch(\n ctx: ContentContext,\n entityIds: string[],\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<Set<string>> {\n validateLocale(locale)\n const result = new Set<string>()\n if (entityIds.length === 0) return result\n const client = await getDraftsClient(ctx)\n if (!client) return result\n\n const rows = await client.findMany({\n where: { entityId: { in: entityIds }, locale },\n })\n for (const row of rows) {\n result.add(row.entityId as string)\n }\n return result\n}\n\n/**\n * Compare the current draft with the live entity. Returns field-level\n * diffs between the published data and the draft (only for fields\n * present in the draft — missing fields are NOT \"changed to empty\").\n */\nexport async function compareDraftWithCurrent<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<{\n diffs: FieldDiff[]\n current: InferEntityDTO<F>\n draft: DraftEntry<InferUpdateInput<F>>\n} | null> {\n validateLocale(locale)\n const draft = await getDraft(ctx, entityId, locale)\n if (!draft) return null\n\n // Fetch the live entity with the same locale context as the draft.\n const config = getContentConfig()\n const defaultLocale = config.defaultLocale\n const findOptions =\n locale === DEFAULT_LOCALE_SENTINEL ? { defaultLocale } : { locale, defaultLocale }\n const current = await ctx.admin.findById(entityId, findOptions)\n if (!current) return null\n\n const fieldConfigs = ctx.entity.allFields as Record<string, FieldConfig> | undefined\n const currentRecord = current as Record<string, unknown>\n const draftRecord = draft.data as Record<string, unknown>\n const currentSubset: Record<string, unknown> = {}\n for (const key of Object.keys(draftRecord)) {\n currentSubset[key] = currentRecord[key]\n }\n const diffs = diffFields(currentSubset, draftRecord, fieldConfigs)\n for (const diff of diffs) {\n if (diff.type === 'blockTree') {\n // Normalize a null/undefined side to [] so add/clear of the whole field\n // (null ↔ blockTree[]) still produces a structural diff, not an opaque one.\n diff.blockDiffs = diffBlocks(\n Array.isArray(diff.from) ? diff.from : [],\n Array.isArray(diff.to) ? diff.to : [],\n )\n }\n }\n\n return { diffs, current, draft }\n}\n","/**\n * Per-locale publish status — independent draft/published state for\n * each locale of a publishable + translatable entity.\n *\n * Capability: requires `publishable() + at least one translatable\n * field` (the `_locale_status` table is registered only for that\n * combination). Reads silently return falsy on entities without it;\n * `setLocaleStatus` throws `EntityCapabilityError`.\n */\n\nimport 'server-only'\n\nimport type { FieldConfig } from '@murumets-ee/entity'\nimport type { InferUpdateInput } from '@murumets-ee/entity/admin'\nimport { EntityCapabilityError } from './errors.js'\nimport { type ContentContext, getLocaleStatusClient } from './internal/context.js'\nimport { upsertLocaleStatusRow } from './locale-status-slot.js'\nimport { validateLocale } from './locale-utils.js'\nimport { getContentConfig } from './plugin.js'\nimport type { LocalePublishStatus } from './types.js'\n\n/**\n * Get per-locale publish status overrides for an entity.\n * Missing locale = inherits the base entity status (no row written).\n *\n * **Not permission-gated, deliberately — see {@link getLocaleStatusBatch}.**\n */\nexport async function getLocaleStatus(\n ctx: ContentContext,\n entityId: string,\n): Promise<LocalePublishStatus[]> {\n const map = await getLocaleStatusBatch(ctx, [entityId])\n const entry = map.get(entityId)\n if (!entry) return []\n return Object.values(entry)\n}\n\n/**\n * Set per-locale publish status. Upserts into the locale_status\n * table — except when `locale === defaultLocale`, which updates the\n * base entity status column directly (the per-locale table only\n * stores overrides for non-default locales).\n *\n * **Both branches are publish-gated by the entity layer (D041).** The default\n * branch inherits it from `AdminClient.update`; the non-default branch routes\n * through `AdminClient.updateForLocale`, which asserts the SAME\n * `assertPublishAuthority` from the caller's payload before it hands the write\n * to the locale-status writer. This is deliberately a delegation and not a\n * second predicate in this package: `<entity>_locale_status` is the table the\n * public read predicate (`COALESCE(locale_status.status, main.status)`) resolves\n * against, so a direct `TableClient.upsert` here — which is what this function\n * used to do — is a fourth publish door, reachable from any plugin/route/job\n * holding a `ContentClient` (a PUBLIC subpath export) with no `publish` grant\n * ever consulted.\n */\nexport async function setLocaleStatus<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale: string,\n status: 'draft' | 'published',\n): Promise<void> {\n validateLocale(locale)\n const config = getContentConfig()\n\n // Default locale → update base entity status column.\n if (locale === config.defaultLocale) {\n const data: Record<string, unknown> = { status }\n if (status === 'published') data.publishedAt = new Date()\n await ctx.admin.update(entityId, data as InferUpdateInput<F>)\n return\n }\n\n const client = await getLocaleStatusClient(ctx)\n if (!client) {\n // Per-locale status only exists for publishable + translatable\n // entities. Calling on a non-translatable publishable (where the\n // only valid locale is the default) is a programmer error.\n // Checked BEFORE delegating: `updateForLocale` would otherwise fall back to\n // the base `status` column for a missing writer, silently publishing the\n // default locale instead of refusing.\n throw new EntityCapabilityError(ctx.entity.name, 'localeStatus')\n }\n\n // The writer we hand down is the RAW upsert, not this function — the\n // delegation terminates here rather than re-entering `updateForLocale`.\n //\n // Routing through `updateForLocale` rather than calling the upsert directly\n // is what closes the publish door: this branch used to write\n // `<entity>_locale_status` with no permission check at all, so any holder of\n // this public export could make a translation publicly live without\n // `publish`. `updateForLocale` asserts publish authority at the operation\n // entry (D041), so the gate is inherited rather than duplicated here.\n //\n // Widened through `Record<string, unknown>` for the same reason the\n // default-locale branch above does it: `InferUpdateInput<F>` is keyed on the\n // entity's own field map, which a generic `F` cannot be proven to overlap.\n const localeData: Record<string, unknown> = { status }\n await ctx.admin.updateForLocale(entityId, localeData as InferUpdateInput<F>, locale, {\n defaultLocale: config.defaultLocale,\n localeStatusWriter: (id, loc, s) => upsertLocaleStatusRow(client, id, loc, s),\n })\n}\n\n/**\n * Get per-locale publish status for multiple entities in one query.\n *\n * ## Why this read is NOT permission-gated (and what would gate it)\n *\n * It returns publish-state METADATA only — `{ locale, status, publishedAt }` —\n * never field data, so it is not a content-disclosure door the way the write\n * side above is a publish door. What it does expose is an existence oracle for\n * unpublished TRANSLATIONS: a principal without `view_unpublished` learns that\n * `et` is a draft, which `QueryClient` would have hidden. The correct predicate\n * is therefore `view_unpublished` (D017), NOT `publish`.\n *\n * A CodeRabbit pass proposed gating it on exactly that predicate. Deliberately\n * declined, on the strength of **F063**: `view_unpublished` governs `QueryClient`\n * reads — the PUBLIC delivery surface — and is not a disclosure boundary over\n * the admin API, where `AdminClient` shows editors their own drafts by design.\n * `ContentClient` is an in-process server-side API whose consumers are plugins,\n * routes and jobs on the admin side, so gating it here would extend the control\n * onto the surface F063 explicitly recommended NOT extending it to. The concrete\n * cost would be an editor lacking `view_unpublished` no longer able to see that\n * their OWN translation is still a draft.\n *\n * The asymmetry with the write side above is real, not convenient:\n * `setLocaleStatus` MINTS public visibility, so it is gated regardless of which\n * surface calls it. This read hands publish-state metadata to a caller who\n * already holds `view` on the row — they needed its id to ask.\n *\n * It is not applied here because the predicate (`mayViewUnpublishedEntity`) is\n * module-private to `@murumets-ee/entity` — re-deriving it in this package\n * would create exactly the second, drifting copy of a security predicate that\n * D041 exists to eliminate, and there is no read-path equivalent of\n * `updateForLocale` to delegate to. The one in-repo caller\n * (`admin-ui`'s versions route) is already gated by `checkPermission`. Closing\n * this properly means exporting the predicate from `@murumets-ee/entity` and\n * dropping non-`published` rows for principals without it — tracked as the\n * read-side sibling of F060.\n */\nexport async function getLocaleStatusBatch(\n ctx: ContentContext,\n entityIds: string[],\n): Promise<Map<string, Record<string, LocalePublishStatus>>> {\n const result = new Map<string, Record<string, LocalePublishStatus>>()\n if (entityIds.length === 0) return result\n const client = await getLocaleStatusClient(ctx)\n if (!client) return result\n\n const rows = await client.findMany({ where: { entityId: { in: entityIds } } })\n for (const r of rows) {\n const eid = r.entityId as string\n const locale = r.locale as string\n let entry = result.get(eid)\n if (!entry) {\n entry = {}\n result.set(eid, entry)\n }\n entry[locale] = {\n locale,\n status: r.status as 'draft' | 'published',\n publishedAt: (r.publishedAt as Date | null) ?? null,\n }\n }\n return result\n}\n","/**\n * Translation status reporting — per-locale completion of translatable\n * fields for one entity, batches of entities, or the whole entity type.\n *\n * Capability: requires the entity to have at least one translatable\n * field. All methods return falsy / empty when the entity has no\n * translatable fields (read-only and defensive).\n */\n\nimport 'server-only'\n\nimport { getContext, requireSiteFor } from '@murumets-ee/core'\nimport { schemaRegistry } from '@murumets-ee/db'\nimport { buildPartitionCondition, type FieldConfig } from '@murumets-ee/entity'\nimport { and, inArray } from 'drizzle-orm'\nimport { InvalidLocaleError } from './errors.js'\nimport type { ContentContext } from './internal/context.js'\nimport { getContentConfig } from './plugin.js'\nimport type { TranslationReport, TranslationStatus } from './types.js'\n\n/**\n * The locales a status report covers and the default it skips: the request's\n * — which the admin narrows to its SITE's locales and default (plan `multisite`\n * phase 03) — else the configured content locales.\n */\nfunction statusLocales(): { locales: { code: string }[]; defaultLocale: string } {\n const config = getContentConfig()\n const ctx = getContext()\n const codes = ctx?.availableLocales ?? config.locales.map((l) => l.code)\n return {\n locales: codes.map((code) => ({ code })),\n defaultLocale: ctx?.defaultLocale ?? config.defaultLocale,\n }\n}\n\n/**\n * For one entity, compute per-locale completion status across every\n * translatable field. Default-locale rows are skipped.\n */\nfunction computeStatusForEntity(\n translatableFields: string[],\n translatedByLocale: Map<string, Record<string, unknown>> | undefined,\n locales: { code: string }[],\n defaultLocale: string,\n): TranslationStatus {\n const status: TranslationStatus = {}\n for (const locale of locales) {\n if (locale.code === defaultLocale) continue\n const translated = translatedByLocale?.get(locale.code) ?? {}\n const missing: string[] = []\n for (const fieldName of translatableFields) {\n if (translated[fieldName] === undefined || translated[fieldName] === null) {\n missing.push(fieldName)\n }\n }\n status[locale.code] = {\n complete: missing.length === 0,\n total: translatableFields.length,\n translated: translatableFields.length - missing.length,\n missing,\n }\n }\n return status\n}\n\n/**\n * Get translation status for an entity — per-locale completion report.\n */\nexport async function getTranslationStatus(\n ctx: ContentContext,\n entityId: string,\n): Promise<TranslationStatus> {\n // Single-entity is the batch path with one ID — keeps the two\n // codepaths from drifting.\n const map = await getTranslationStatusBatch(ctx, [entityId])\n return map.get(entityId) ?? {}\n}\n\n/**\n * Get translation status for multiple entities in a single query.\n * O(1) DB roundtrips regardless of `entityIds.length`.\n */\nexport async function getTranslationStatusBatch(\n ctx: ContentContext,\n entityIds: string[],\n): Promise<Map<string, TranslationStatus>> {\n const result = new Map<string, TranslationStatus>()\n if (entityIds.length === 0) return result\n\n const { locales, defaultLocale } = statusLocales()\n\n const translatableFields = Object.entries(ctx.entity.allFields as Record<string, FieldConfig>)\n .filter(([_, f]) => f.translatable)\n .map(([name]) => name)\n if (translatableFields.length === 0) return result\n\n // Translation tables are generated in @murumets-ee/entity (with FK\n // refs); accessed via schemaRegistry + direct Drizzle here.\n const translationTable = schemaRegistry.get(`${ctx.entity.name}_translations`)\n if (!translationTable) return result\n\n // A site-bound entity's translation rows are confined to the request's\n // site (multisite D003): ids alone are no boundary — a caller holding\n // another site's id must learn nothing about its translations.\n const site = await requireSiteFor(ctx.entity)\n const byIds = inArray(translationTable.entityId, entityIds)\n const translations = await ctx.db\n .select()\n .from(translationTable)\n .where(\n site !== undefined\n ? and(byIds, buildPartitionCondition(translationTable, { site }, ctx.entity.name))\n : byIds,\n )\n\n // Group: entityId → locale → { fieldName: value }\n const translationsByEntity = new Map<string, Map<string, Record<string, unknown>>>()\n for (const t of translations) {\n const row = t as Record<string, unknown>\n const eid = row.entityId as string\n const locale = row.locale as string\n const fieldValues: Record<string, unknown> = {}\n for (const fieldName of translatableFields) {\n fieldValues[fieldName] = row[fieldName]\n }\n let entry = translationsByEntity.get(eid)\n if (!entry) {\n entry = new Map()\n translationsByEntity.set(eid, entry)\n }\n entry.set(locale, fieldValues)\n }\n\n for (const entityId of entityIds) {\n result.set(\n entityId,\n computeStatusForEntity(\n translatableFields,\n translationsByEntity.get(entityId),\n locales,\n defaultLocale,\n ),\n )\n }\n\n return result\n}\n\n/**\n * Roll up translation status across every entity of this type.\n *\n * Defaults to the first non-default configured locale; pass\n * `options.locale` to target a specific one. Returns counts of\n * complete / partial / missing entities for that locale.\n */\nexport async function getTranslationReport(\n ctx: ContentContext,\n options?: { locale?: string },\n): Promise<TranslationReport> {\n const { locales, defaultLocale } = statusLocales()\n const targetLocale = options?.locale ?? locales.find((l) => l.code !== defaultLocale)?.code\n if (!targetLocale) return { total: 0, complete: 0, partial: 0, missing: 0 }\n // A locale the site does not serve has no report on that site.\n if (!locales.some((l) => l.code === targetLocale)) {\n throw new InvalidLocaleError(\n targetLocale,\n locales.map((l) => l.code),\n )\n }\n\n const entities = await ctx.admin.findMany()\n if (entities.length === 0) return { total: 0, complete: 0, partial: 0, missing: 0 }\n\n // Single batched query covers every entity at once.\n const statusMap = await getTranslationStatusBatch(\n ctx,\n entities.map((e) => e.id),\n )\n\n let complete = 0\n let partial = 0\n let missing = 0\n for (const entity of entities) {\n const status = statusMap.get(entity.id)\n const localeStatus = status?.[targetLocale]\n if (!localeStatus || localeStatus.translated === 0) missing++\n else if (localeStatus.complete) complete++\n else partial++\n }\n\n return { total: entities.length, complete, partial, missing }\n}\n","/**\n * ContentClient — thin shell over per-feature modules.\n *\n * Wraps AdminClient with version history (`./versions.ts`), draft\n * overlays (`./drafts.ts`), translation status reporting\n * (`./translation-status.ts`), per-locale publish status\n * (`./locale-status.ts`), and block-layout operations (`./layout.ts`).\n *\n * The class is generic over the entity's `AllFields` map: when\n * constructed with a typed entity, every method's input/output is\n * inferred end-to-end. When constructed with a runtime `Entity`\n * (admin-ui's heterogeneous entity loops), the generic defaults to\n * `Record<string, FieldConfig>` and methods accept/return the loose\n * shape — same behavior as the pre-generic version.\n *\n * Usage:\n * import { createContentClient } from '@murumets-ee/content/client'\n * const pages = createContentClient(Page)\n * await pages.create({ title: 'Hello', layout: [...] })\n */\n\nimport 'server-only'\n\nimport { getApp, type Logger } from '@murumets-ee/core'\nimport { createAdminClient } from '@murumets-ee/core/clients'\nimport type { Entity, FieldConfig } from '@murumets-ee/entity'\nimport type {\n AdminClient,\n FindManyOptions,\n InferCreateInput,\n InferEntityDTO,\n InferUpdateInput,\n} from '@murumets-ee/entity/admin'\nimport { getVersionableOptions } from './behaviors/versionable.js'\nimport {\n compareDraftWithCurrent,\n countDrafts,\n deleteDraft,\n getDraft,\n hasDraft,\n hasDraftBatch,\n mergeDraft,\n publishDraft,\n saveDraft,\n} from './drafts.js'\nimport { type ContentContext, createContentContext } from './internal/context.js'\nimport { calculateDelta } from './internal/projection.js'\nimport { getLocaleStatus, getLocaleStatusBatch, setLocaleStatus } from './locale-status.js'\nimport {\n getTranslationReport,\n getTranslationStatus,\n getTranslationStatusBatch,\n} from './translation-status.js'\nimport {\n compareVersions,\n createVersionSnapshot,\n getVersion,\n getVersions,\n pruneVersions,\n restoreVersion,\n saveVersionSnapshot,\n writeVersionColumn,\n} from './versions.js'\n\nexport interface ContentClientConfig<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n admin: AdminClient<AllFields>\n entity: Entity<AllFields>\n logger?: Logger\n}\n\nexport class ContentClient<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n private ctx: ContentContext<AllFields>\n\n constructor(config: ContentClientConfig<AllFields>) {\n const versionableOptions = getVersionableOptions(config.entity.behaviors)\n this.ctx = createContentContext(config, versionableOptions)\n }\n\n // -----------------------------------------------------------------\n // CRUD (delegated to AdminClient + version snapshots)\n // -----------------------------------------------------------------\n\n async create(data: InferCreateInput<AllFields>): Promise<InferEntityDTO<AllFields>> {\n const result = await this.ctx.admin.create(data)\n if (this.ctx.versionableOptions) {\n await saveVersionSnapshot(this.ctx, result.id, result, null, false)\n }\n return result\n }\n\n findById(id: string, options?: { locale?: string }): Promise<InferEntityDTO<AllFields> | null> {\n return this.ctx.admin.findById(id, options)\n }\n\n findMany(options?: FindManyOptions): Promise<InferEntityDTO<AllFields>[]> {\n return this.ctx.admin.findMany(options)\n }\n\n /**\n * Base-row update + version snapshot. Subject to AdminClient's\n * cross-locale write guard (SD021): under a non-default request-context\n * locale, translatable fields throw `CrossLocaleWriteError` — that's\n * enforcement, not a gap. Locale-belonging writes go through the draft\n * flow (`saveDraft` → `publishDraft`) or `admin.updateForLocale` directly.\n */\n async update(id: string, data: InferUpdateInput<AllFields>): Promise<InferEntityDTO<AllFields>> {\n let previousState: InferEntityDTO<AllFields> | null = null\n if (this.ctx.versionableOptions) {\n previousState = await this.ctx.admin.findById(id)\n }\n\n const result = await this.ctx.admin.update(id, data)\n\n if (this.ctx.versionableOptions && previousState) {\n const delta = calculateDelta(previousState, result)\n const version = await saveVersionSnapshot(this.ctx, id, result, delta, false)\n if (version !== undefined) {\n await writeVersionColumn(this.ctx, id, version)\n await pruneVersions(this.ctx, id)\n return { ...result, _version: version } as InferEntityDTO<AllFields>\n }\n await pruneVersions(this.ctx, id)\n }\n\n return result\n }\n\n delete(id: string): Promise<unknown> {\n return this.ctx.admin.delete(id)\n }\n\n // -----------------------------------------------------------------\n // Translation delegation\n // -----------------------------------------------------------------\n\n saveTranslation(entityId: string, locale: string, translations: Record<string, unknown>) {\n return this.ctx.admin.saveTranslation(entityId, locale, translations)\n }\n\n deleteTranslation(entityId: string, locale?: string) {\n return this.ctx.admin.deleteTranslation(entityId, locale)\n }\n\n // -----------------------------------------------------------------\n // Version history\n // -----------------------------------------------------------------\n\n getVersions(entityId: string, options?: { limit?: number; offset?: number; locale?: string }) {\n return getVersions(this.ctx, entityId, options)\n }\n\n getVersion(entityId: string, version: number, locale?: string) {\n return getVersion(this.ctx, entityId, version, locale)\n }\n\n compareVersions(entityId: string, v1: number, v2: number, locale?: string) {\n return compareVersions(this.ctx, entityId, v1, v2, locale)\n }\n\n restoreVersion(entityId: string, version: number, locale?: string) {\n return restoreVersion(this.ctx, entityId, version, locale)\n }\n\n pruneVersions(entityId: string, locale?: string) {\n return pruneVersions(this.ctx, entityId, locale)\n }\n\n createVersionSnapshot(\n entityId: string,\n currentData: Record<string, unknown>,\n previousData?: Record<string, unknown> | null,\n locale?: string,\n user?: { id: string; name?: string },\n ) {\n return createVersionSnapshot(this.ctx, entityId, currentData, previousData, locale, user)\n }\n\n // -----------------------------------------------------------------\n // Translation status\n // -----------------------------------------------------------------\n\n getTranslationStatus(entityId: string) {\n return getTranslationStatus(this.ctx, entityId)\n }\n\n getTranslationStatusBatch(entityIds: string[]) {\n return getTranslationStatusBatch(this.ctx, entityIds)\n }\n\n getTranslationReport(options?: { locale?: string }) {\n return getTranslationReport(this.ctx, options)\n }\n\n // -----------------------------------------------------------------\n // Per-locale publish status\n // -----------------------------------------------------------------\n\n getLocaleStatus(entityId: string) {\n return getLocaleStatus(this.ctx, entityId)\n }\n\n setLocaleStatus(entityId: string, locale: string, status: 'draft' | 'published') {\n return setLocaleStatus(this.ctx, entityId, locale, status)\n }\n\n getLocaleStatusBatch(entityIds: string[]) {\n return getLocaleStatusBatch(this.ctx, entityIds)\n }\n\n // -----------------------------------------------------------------\n // Drafts\n // -----------------------------------------------------------------\n\n saveDraft(\n entityId: string,\n data: InferUpdateInput<AllFields>,\n locale?: string,\n user?: { id: string; name?: string },\n ) {\n return saveDraft(this.ctx, entityId, data, locale, user)\n }\n\n mergeDraft(\n entityId: string,\n patch: InferUpdateInput<AllFields>,\n locale?: string,\n user?: { id: string; name?: string },\n ) {\n return mergeDraft(this.ctx, entityId, patch, locale, user)\n }\n\n getDraft(entityId: string, locale?: string) {\n return getDraft(this.ctx, entityId, locale)\n }\n\n deleteDraft(entityId: string, locale?: string) {\n return deleteDraft(this.ctx, entityId, locale)\n }\n\n publishDraft(entityId: string, locale?: string, user?: { id: string; name?: string }) {\n return publishDraft(this.ctx, entityId, locale, user)\n }\n\n hasDraft(entityId: string, locale?: string) {\n return hasDraft(this.ctx, entityId, locale)\n }\n\n countDrafts(locale?: string) {\n return countDrafts(this.ctx, locale)\n }\n\n hasDraftBatch(entityIds: string[], locale?: string) {\n return hasDraftBatch(this.ctx, entityIds, locale)\n }\n\n compareDraftWithCurrent(entityId: string, locale?: string) {\n return compareDraftWithCurrent(this.ctx, entityId, locale)\n }\n}\n\n/**\n * Factory — creates a ContentClient for an entity. Must be called\n * after `createApp()`. Generic flows from the entity definition:\n * `createContentClient(Article)` returns a `ContentClient<typeof\n * Article['allFields']>` typed end-to-end.\n */\nexport function createContentClient<AllFields extends Record<string, FieldConfig>>(\n entity: Entity<AllFields>,\n): ContentClient<AllFields> {\n const admin = createAdminClient(entity)\n return new ContentClient<AllFields>({\n admin,\n entity,\n logger: getApp().logger.child({ content: entity.name }),\n })\n}\n"],"mappings":"2wBA+BA,SAAS,EAAa,EAA2B,CAC/C,MAAO,CACL,GAAI,EAAI,GACR,SAAU,EAAI,SACd,OAAQ,EAAI,OACZ,KAAM,EAAI,KACV,UAAW,EAAI,UACf,cAAe,EAAI,eAAiB,KACpC,UAAW,EAAI,UACf,UAAW,EAAI,SACjB,CACF,CAOA,eAAe,EACb,EACA,EACA,EAC8C,CAC9C,GAAI,CAKF,OAAQ,MAJU,EAAI,MAAM,SAC1B,EACA,IAAA,IAAqC,CAAC,EAAI,CAAE,QAAO,CACrD,GACkD,IAAA,EACpD,OAAS,EAAO,CACd,EAAI,QAAQ,KACV,CAAE,OAAQ,EAAI,OAAO,KAAM,WAAU,OAAM,EAC3C,qEACF,EACA,MACF,CACF,CAOA,eAAe,EACb,EACA,EACA,EACA,EACA,EAC8C,CAC9C,IAAM,EACkB,OAAO,GAAc,UAA3C,EACK,EACD,IAAA,GAIN,GAAI,CAHY,EAAkB,EAAI,MAAM,CAAC,CAAC,MAC3C,CAAE,UAAW,OAAO,OAAO,EAAW,CAAI,GAAK,CAAC,MAAM,QAAQ,IAAQ,EAAK,CAEnE,EAAG,OAAO,EACrB,IAAM,EAAO,MAAM,EAAQ,EAAK,EAAU,CAAM,EAEhD,OADI,IAAS,IAAA,GAAkB,EACxB,CAAE,GAAG,EAAM,G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,EAAiB,CAC1C,OAAO,EAAS,KAAK,IAAK,EAAU,CAAM,CAC5C,CAEA,YAAY,EAAiB,CAC3B,OAAO,EAAY,KAAK,IAAK,CAAM,CACrC,CAEA,cAAc,EAAqB,EAAiB,CAClD,OAAO,EAAc,KAAK,IAAK,EAAW,CAAM,CAClD,CAEA,wBAAwB,EAAkB,EAAiB,CACzD,OAAO,EAAwB,KAAK,IAAK,EAAU,CAAM,CAC3D,CACF,EAQA,SAAgB,GACd,EAC0B,CAE1B,OAAO,IAAI,EAAyB,CAClC,MAFY,EAAkB,CAE1B,EACJ,SACA,OAAQ,EAAO,CAAC,CAAC,OAAO,MAAM,CAAE,QAAS,EAAO,IAAK,CAAC,CACxD,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"client.mjs","names":[],"sources":["../src/drafts.ts","../src/locale-status.ts","../src/translation-status.ts","../src/client.ts"],"sourcesContent":["/**\n * Draft-overlay operations.\n *\n * Capability: requires the entity to declare `publishable()`. Reads\n * (`getDraft`, `hasDraft`, `countDrafts`, `hasDraftBatch`) silently\n * return falsy when the entity doesn't support drafts; writes\n * (`saveDraft`, `mergeDraft`, `publishDraft`) throw `EntityCapabilityError`.\n */\n\nimport 'server-only'\n\nimport { blockTreeFieldsOf, type FieldConfig } from '@murumets-ee/entity'\nimport type { InferEntityDTO, InferUpdateInput } from '@murumets-ee/entity/admin'\nimport { diffBlocks } from './diff/block-diff.js'\nimport { diffFields } from './diff/field-diff.js'\nimport type { FieldDiff } from './diff/types.js'\nimport { DraftNotFoundError, EntityCapabilityError } from './errors.js'\nimport {\n applyLocaleRoutedUpdate,\n localeFindOptions,\n} from './internal/apply-locale-routed-update.js'\nimport { type ContentContext, getDraftsClient } from './internal/context.js'\nimport { projectToEntityFields } from './internal/projection.js'\nimport { DEFAULT_LOCALE_SENTINEL, validateLocale } from './locale-utils.js'\nimport { getContentConfig } from './plugin.js'\nimport type { DraftsTable } from './schema/drafts.js'\nimport { recordLocaleSave } from './translation-provenance.js'\nimport type { DraftEntry } from './types.js'\nimport { createVersionSnapshot } from './versions.js'\n\ntype DraftRow = NonNullable<Awaited<ReturnType<ReturnType<DraftsTable['makeClient']>['findOne']>>>\n\nfunction toDraftEntry(row: DraftRow): DraftEntry {\n return {\n id: row.id,\n entityId: row.entityId,\n locale: row.locale,\n data: row.data,\n createdBy: row.createdBy,\n createdByName: row.createdByName ?? null,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n }\n}\n\n/**\n * The live row behind a draft, in the draft's locale — `undefined` when it\n * cannot be read. Never throws: the caller treats an unreadable row as \"no\n * stored copy\", which is the strict answer.\n */\nasync function liveRow<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale: string,\n): Promise<Record<string, unknown> | undefined> {\n try {\n const row = await ctx.admin.findById(\n entityId,\n locale === DEFAULT_LOCALE_SENTINEL ? {} : { locale },\n )\n return (row as Record<string, unknown> | null) ?? undefined\n } catch (error) {\n ctx.logger?.warn(\n { entity: ctx.entity.name, entityId, error },\n 'draft: the live row could not be read to grandfather its block tree',\n )\n return undefined\n }\n}\n\n/**\n * What a draft save's block trees are judged AGAINST: the stored draft's tree\n * for a field the draft already holds, the live row's for one it does not.\n * The live row is read only in the second case.\n */\nasync function storedTreesFor<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale: string,\n projected: Record<string, unknown>,\n draftData: unknown,\n): Promise<Record<string, unknown> | undefined> {\n const draft =\n draftData !== null && typeof draftData === 'object'\n ? (draftData as Record<string, unknown>)\n : undefined\n const missing = blockTreeFieldsOf(ctx.entity).some(\n ({ name }) => Object.hasOwn(projected, name) && !Array.isArray(draft?.[name]),\n )\n if (!missing) return draft\n const live = await liveRow(ctx, entityId, locale)\n if (live === undefined) return draft\n return { ...live, ...draft }\n}\n\n/**\n * Save (upsert) a draft for an entity+locale. One draft per\n * entity+locale — overwrites any existing draft.\n *\n * `data` is projected through the entity's declared field whitelist\n * BEFORE it is stored (same `projectToEntityFields` call `publishDraft`\n * makes on the way out). Storing the caller's JSON verbatim let a draft\n * carry keys the entity never declared, identity/audit columns and\n * `internal: true` fields; publishing filtered them, but `getDraft` and\n * `compareDraftWithCurrent` echoed them straight back to the admin UI,\n * and the drafts table accumulated arbitrary caller-controlled JSON\n * (`plan/admin-api-hardening` F002). Validating at the write closes the\n * asymmetry — the stored draft is now always a subset of what the entity\n * can actually hold.\n */\nexport async function saveDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n data: InferUpdateInput<F>,\n locale = DEFAULT_LOCALE_SENTINEL,\n user?: { id: string; name?: string },\n): Promise<DraftEntry<InferUpdateInput<F>>> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n\n const projected = projectToEntityFields(ctx.entity, data as Record<string, unknown>)\n\n // `projectToEntityFields` is a field-NAME whitelist — it never inspects a\n // value, so a `field.blockTree()` column in a draft took arbitrary JSON, and\n // `editor-state` hands the stored draft back as the CANVAS BASE STATE\n // (editor F002). Publishing is already gated by the entity write path, but\n // waiting until publish means the editor loads a tree it cannot represent.\n // Same validator, same judgement — asked here because the draft blob carries\n // no Zod schema of its own.\n ctx.admin.assertBlockTreesValid(projected)\n // …and the STRICT judgement for a token-derived caller (agent-access D014):\n // a draft is published later by whoever presses Publish, so a tree a machine\n // could not store directly must not be parked here for a person to promote.\n // F116, same reasoning — and this is precisely the write path the finding\n // was filed against: dava's home-page DRAFT already holds a mismatched\n // media reference. Grandfathering against the draft ALREADY STORED (rather\n // than validating strictly) is what keeps that draft's next autosave\n // working instead of turning \"a broken image\" into \"a draft that can never\n // be saved again\".\n //\n // The lookup is skipped entirely when the PROJECTED payload carries no\n // block-tree field at all — `assertMediaKindsValid` would no-op anyway\n // (same optimization as `saveTranslation`'s), and most entities with\n // drafts have no block-tree field to begin with.\n const hasBlockTreeValue = blockTreeFieldsOf(ctx.entity).some(({ name }) =>\n Object.hasOwn(projected, name),\n )\n const existing = hasBlockTreeValue ? await client.findOne({ entityId, locale }) : null\n // Grandfathered against the draft already stored, like the media-kind check\n // below: a tree that was there before this save is not what this save adds.\n // With no draft yet, against the live row — a first draft of a document\n // whose live tree holds a block no longer placeable there must still save\n // (davatoidud-toolkit D006).\n await ctx.admin.assertBlockTreesFitDocument(\n projected,\n () => storedTreesFor(ctx, entityId, locale, projected, existing?.data),\n { loadAreaRow: () => liveRow(ctx, entityId, locale) },\n )\n await ctx.admin.assertMediaKindsValid(\n projected,\n existing?.data as Record<string, unknown> | undefined,\n )\n\n const now = new Date()\n const createdBy = user?.id ?? ''\n const createdByName = user?.name ?? null\n\n const row = await client.upsert(\n {\n entityId,\n locale,\n data: projected,\n createdBy,\n createdByName,\n createdAt: now,\n updatedAt: now,\n },\n {\n target: ['entityId', 'locale'],\n // On conflict, only update the mutable fields — preserve createdBy/createdAt.\n set: { data: projected, updatedAt: now },\n },\n )\n\n // What this locale was saved from (agent-access D017) — never fails the save.\n await recordLocaleSave({\n entityName: ctx.entity.name,\n entityId,\n locale,\n userId: user?.id,\n draftData: (row.data as Record<string, unknown> | undefined) ?? {},\n })\n return toDraftEntry(row) as DraftEntry<InferUpdateInput<F>>\n}\n\n/**\n * The keys that move a document's canonical URL in the patterns the toolkit\n * ships (`[slug]`, `[parent.path]`) plus the slug mode that decides whether a\n * clash is refused or auto-suffixed. A merge naming one of them, on a ROUTABLE\n * entity, runs the path-conflict check (see `mergeDraft`); any other merge\n * skips its lookups — the staged draft, the row, and `toolkit_paths` (twice\n * under a parent).\n *\n * A pattern built from another field (`/[category]/[slug]`) is not covered:\n * staging only `category` is refused at Publish rather than here.\n */\nconst PATH_KEYS = ['slug', 'slugMode', 'parent'] as const\n\n/**\n * Stage a PARTIAL change: merge `patch` into the entity+locale draft, creating\n * the draft if there is none. Keys not in `patch` are left exactly as the draft\n * (or, absent a draft key, the live row) has them.\n *\n * This is the write every editing surface uses since editor D019 — \"every edit\n * on every surface saves to the document's one shared draft\". `saveDraft`\n * REPLACES the blob, which is right for a surface that owns the whole document\n * (the menu editor) and wrong for one that owns a few fields of it: page\n * settings saving `title` through `saveDraft` would erase the block edits the\n * canvas staged a second earlier. A draft is therefore a patch over the row, and\n * every reader that shows editable values reads row ⊕ draft.\n *\n * Judged like the entity PATCH it replaces, BEFORE it is stored:\n * - projected through the field whitelist (`internal`, undeclared keys dropped)\n * - `assertBlockTreesValid` + `assertMediaKindsValid` (grandfathered against the\n * stored draft, same as `saveDraft`)\n * - `assertUpdateValid` — the entity's own update schema. `saveDraft` never ran\n * it, which was harmless while the form's Publish still PATCHed; moving a\n * surface into the draft must not move its refusal to Publish, where the\n * author is no longer looking at the field.\n * - `assertPathAvailable` — the path-conflict guard, as a dry run, when the\n * merge moves the URL (see {@link PATH_KEYS}) on a routable entity (F150).\n *\n * 🔴 ONE STATEMENT, not read-modify-write. The merge is `data || patch` inside\n * `ON CONFLICT DO UPDATE` (`TableClient.upsert`'s `mergeJsonb`), so it cannot\n * lose a concurrent write: a read-then-upsert that interleaved with op-commit's\n * or a bound field's stage would write back the draft as it was read — silently\n * reverting the other writer's change. `writeDraft` merges the same way, so\n * neither can erase the other. Top-level `||`, a SHALLOW merge.\n *\n * Resolves `null` when the projected patch is EMPTY and no draft exists: nothing\n * the entity declares was sent, so nothing is staged and no empty draft row is\n * created.\n *\n * ⚠️ The rest of the write path's hooks — `pathParent()`'s cycle check, the\n * partial-unique slug index, `sluggable()`'s regeneration — still run only at\n * Publish, inside its transaction, where a refusal stops the whole publish. The\n * path check here answers \"as of now\"; Publish runs the real guard again.\n */\nexport async function mergeDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n patch: InferUpdateInput<F>,\n locale = DEFAULT_LOCALE_SENTINEL,\n user?: { id: string; name?: string },\n): Promise<DraftEntry<InferUpdateInput<F>> | null> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n\n const projected = projectToEntityFields(ctx.entity, patch as Record<string, unknown>)\n // Nothing the entity declares: stage nothing. Upserting `{}` would CREATE an\n // empty draft, and the document would then read \"Draft saved · not live\n // yet\" about a change that does not exist.\n if (Object.keys(projected).length === 0) {\n const current = await client.findOne({ entityId, locale })\n return current ? (toDraftEntry(current) as DraftEntry<InferUpdateInput<F>>) : null\n }\n ctx.admin.assertBlockTreesValid(projected)\n ctx.admin.assertUpdateValid(projected)\n const hasBlockTreeValue = blockTreeFieldsOf(ctx.entity).some(({ name }) =>\n Object.hasOwn(projected, name),\n )\n const touchesPath =\n ctx.entity.frontend?.path !== undefined &&\n PATH_KEYS.some((key) => Object.hasOwn(projected, key))\n const existing =\n hasBlockTreeValue || touchesPath ? await client.findOne({ entityId, locale }) : null\n // The contextual judgement — the document's area for everyone, the strict\n // tree for a token-derived caller (agent-access D014) — with the stored\n // draft, or the live row when there is none, to grandfather against. See\n // `saveDraft`.\n await ctx.admin.assertBlockTreesFitDocument(\n projected,\n () => storedTreesFor(ctx, entityId, locale, projected, existing?.data),\n { loadAreaRow: () => liveRow(ctx, entityId, locale) },\n )\n await ctx.admin.assertMediaKindsValid(\n projected,\n existing?.data as Record<string, unknown> | undefined,\n )\n // A staged slug that another document's URL already holds is refused NOW,\n // beside the field the author typed it in — not first at Publish (editor\n // PR60, F150). Checked against what the draft will hold after this merge,\n // since an earlier stage may have set `slugMode` or `parent`.\n if (touchesPath) {\n const staged = {\n ...((existing?.data as Record<string, unknown> | undefined) ?? {}),\n ...projected,\n }\n if (locale === DEFAULT_LOCALE_SENTINEL) {\n await ctx.admin.assertPathAvailable(entityId, staged)\n } else {\n // Checked the way Publish writes it: `updateForLocale` sends a locale's\n // TRANSLATABLE fields through that locale's guard and the rest (a\n // `parent`, a non-translatable slug) through `update()`, whose guard\n // checks the default locale. One guard over everything would test a\n // shared `parent` against the wrong locale's URLs.\n const fields = ctx.entity.allFields as Record<string, { translatable?: boolean } | undefined>\n const translatable: Record<string, unknown> = {}\n const shared: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(staged)) {\n if (fields[key]?.translatable === true) translatable[key] = value\n else shared[key] = value\n }\n const moves = (part: Record<string, unknown>) =>\n PATH_KEYS.some((key) => Object.hasOwn(part, key) && Object.hasOwn(projected, key))\n if (moves(translatable)) await ctx.admin.assertPathAvailable(entityId, translatable, locale)\n if (moves(shared)) await ctx.admin.assertPathAvailable(entityId, shared)\n }\n }\n\n const now = new Date()\n const row = await client.upsert(\n {\n entityId,\n locale,\n data: projected,\n createdBy: user?.id ?? '',\n createdByName: user?.name ?? null,\n createdAt: now,\n updatedAt: now,\n },\n { target: ['entityId', 'locale'], set: { updatedAt: now }, mergeJsonb: ['data'] },\n )\n // What this locale was saved from (agent-access D017) — never fails the save.\n await recordLocaleSave({\n entityName: ctx.entity.name,\n entityId,\n locale,\n userId: user?.id,\n draftData: (row.data as Record<string, unknown> | undefined) ?? {},\n })\n return toDraftEntry(row) as DraftEntry<InferUpdateInput<F>>\n}\n\n/**\n * Get the draft for an entity+locale, or null if none exists (or the\n * entity doesn't support drafts).\n */\nexport async function getDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<DraftEntry<InferUpdateInput<F>> | null> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) return null\n const row = await client.findOne({ entityId, locale })\n return row ? (toDraftEntry(row) as DraftEntry<InferUpdateInput<F>>) : null\n}\n\n/**\n * Delete (discard) a draft for an entity+locale. Returns whether\n * anything was deleted; safely no-ops on entities without drafts.\n */\nexport async function deleteDraft(\n ctx: ContentContext,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<boolean> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) return false\n const deleted = await client.deleteMany({ entityId, locale })\n // Discarding a draft changes the locale's working text back to the row's\n // (agent-access D017) — record it, or a discarded SOURCE edit keeps every\n // translation reading \"outdated\". `reverted`: nobody wrote a word, so an\n // agent's discard is not machine output. What this does NOT do: un-mark a\n // locale whose discarded draft was a machine translation — one row per locale\n // cannot say what the live row underneath was, so it keeps reading \"not\n // reviewed\" until someone reviews it or saves it.\n if (deleted.length > 0) {\n await recordLocaleSave({ entityName: ctx.entity.name, entityId, locale, reverted: true })\n }\n return deleted.length > 0\n}\n\n/**\n * Publish a draft: make THIS document's staged changes live.\n *\n * \"Publish\" means one thing on every surface (editor D019): the draft's fields\n * are written to the row for the draft's locale AND the row is put live. The\n * draft is then gone and, if versionable, a version snapshot records what went\n * live.\n *\n * Locale routing mirrors the admin PATCH handler (and the taxonomy fix\n * in 10a7cc2b): a default-locale draft writes the base row; a\n * non-default-locale draft routes translatable fields to\n * `saveTranslation` (→ `{entity}_translations`), `status` to the\n * per-locale status table, and only non-translatable fields (which have\n * no per-locale home) to the base row. Without this split, publishing\n * an `et` draft overwrote the default-locale base row wholesale.\n *\n * ## ONE TRANSACTION (editor PR60, R055 §4)\n *\n * The row write, the locale status, `_overrides`, the draft delete and the\n * version snapshot commit together or not at all. They used to be five separate\n * statements, so a failure part-way left a document whose content was live and\n * whose draft still claimed to be pending — or, worse, whose draft was gone while\n * the row write had not landed.\n *\n * The draft is CLAIMED first, by deleting it and publishing what the delete\n * returned. The delete takes the row lock, so an op-commit that is mid-flight on\n * the same draft either committed before (and its edit is in what we publish) or\n * blocks until we commit and then retries its SERIALIZABLE transaction — or, if it\n * had not read the draft yet, inserts a fresh draft holding only its own patch.\n * Either way it does not write a stale copy back over the published one. The editor also flushes and awaits its own in-flight saves\n * before it calls this, so the lock is the backstop, not the mechanism.\n *\n * Path-index and write notifications fire after COMMIT, not inside it —\n * `AdminClient.afterCommit` defers them on a tracked transaction.\n */\nexport async function publishDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n user?: { id: string; name?: string },\n): Promise<InferEntityDTO<F>> {\n validateLocale(locale)\n if (!(await getDraftsClient(ctx))) {\n throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n }\n\n // Previous state for the version delta — locale-merged, so the delta compares\n // against what this locale's readers actually saw. Read BEFORE the\n // transaction: it is the committed state the publish replaces.\n const previousState: InferEntityDTO<F> | null = ctx.versionableOptions\n ? await ctx.admin.findById(entityId, localeFindOptions(locale))\n : null\n\n return ctx.db.transaction(async (tx) => {\n // Every table client below binds to `tx` through this context — drafts,\n // locale status, versions and the `_version` column write.\n const txCtx: ContentContext<F> = { ...ctx, db: tx }\n const draftsClient = await getDraftsClient(txCtx)\n if (!draftsClient) throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n const [claimed] = await draftsClient.deleteMany({ entityId, locale })\n if (!claimed) {\n throw new DraftNotFoundError(entityId, locale)\n }\n\n // `?? {}` because the column is `jsonb NOT NULL`, and that forbids SQL NULL\n // while permitting the JSON literal `null` — which deserializes to JS `null`.\n // A bare cast then made `draftData.status` a TypeError, so a malformed row\n // 500'd the publish route instead of taking the ordinary \"nothing declared,\n // publish the row as-is\" path below. Nothing in this package writes such a\n // row; a seed, a migration or a hand-edit can.\n const claimedData = (claimed.data ?? {}) as Record<string, unknown>\n // `publishedAt` is Publish's to set, like `status` below: a staged value\n // would let whoever wrote the draft back- or forward-date the publication.\n // publishable()'s hook fills it when the UPDATE carries none — which, with\n // the staged value dropped, is every publish: it records the LATEST\n // publication, not the first.\n const { publishedAt: _stagedPublishedAt, ...draftData } = claimedData\n // \"Publish\" means MAKE LIVE, always — the status is not the draft's to\n // decide. Block-editor drafts carry no `status` at all, and before D019 a\n // form-saved draft could carry `status: 'draft'`, which then won: Publish\n // wrote the content and left the document unpublished, so the same button\n // meant \"publish\" on one surface and \"stage\" on another. The publishable()\n // behavior auto-sets `publishedAt` on the transition. The publish-permission\n // gate lives in the admin route, not here.\n const updateData = projectToEntityFields(ctx.entity, { ...draftData, status: 'published' })\n const result = await applyLocaleRoutedUpdate(txCtx, entityId, updateData, locale, tx)\n\n // F009 — promote the page's chrome overrides.\n //\n // `projectToEntityFields` drops every `internal: true` field, deliberately, so\n // `_overrides` cannot ride the generic promotion. That guard is NOT relaxed:\n // this is one named field, written through the trusted `updateInternal` path\n // that `with-overrides.ts` documents as \"the only path that can mutate it\".\n // Before F009 that call site did not exist, so an override survived in the\n // draft buffer and never reached the column — the op committed, the canvas\n // updated, and a reload brought the hidden header back.\n //\n // AFTER the main update, so the override never lands against content that\n // failed to — and inside the same transaction, so neither lands alone.\n // `_overrides` is not translatable, so it belongs on the base row for every\n // locale.\n const overrides = readOverridesForPublish(ctx.entity, draftData)\n if (overrides !== undefined) {\n await ctx.admin.updateInternal(entityId, { _overrides: overrides }, { tx })\n }\n\n if (ctx.versionableOptions) {\n await createVersionSnapshot(txCtx, entityId, result, previousState, locale, user)\n }\n\n return result\n })\n}\n\n/**\n * The page's override map from a draft payload, when the entity declares the\n * field and the draft carries one.\n *\n * Returns `undefined` — never `{}` — so an ordinary content publish does not\n * touch the column. Shape-guarded because a draft payload is stored jsonb: an\n * array or a scalar is malformed data, not an override map. ← F009\n */\nfunction readOverridesForPublish(\n entity: { allFields: Record<string, unknown>; behaviors?: readonly { name: string }[] },\n draftData: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n // The BEHAVIOR, not just a field with the right name — a draft payload is\n // stored jsonb and can be crafted or legacy, so this must not become a way\n // to promote arbitrary JSON into an unrelated internal field on an entity\n // that never opted in. Requiring the behavior also means `beforeUpdate` runs\n // `validateOverridesMap` on the way through `updateInternal`.\n if (!(entity.behaviors ?? []).some((b) => b.name === 'withOverrides')) return undefined\n const field = entity.allFields._overrides as { internal?: boolean } | undefined\n if (field === undefined || field.internal !== true) return undefined\n const value = draftData._overrides\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n return value as Record<string, unknown>\n}\n\n/**\n * Quick existence check for list badges — does a draft exist?\n */\nexport async function hasDraft(\n ctx: ContentContext,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<boolean> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) return false\n return client.exists({ entityId, locale })\n}\n\n/**\n * Count drafts for this entity type, optionally filtered by locale.\n * Single indexed COUNT — used by dashboard widgets.\n */\nexport async function countDrafts(\n ctx: ContentContext,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<number> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) return 0\n return client.count({ locale })\n}\n\n/**\n * Check draft existence for multiple entities in one query. Returns\n * a set of entity IDs that have a draft for `locale`.\n */\nexport async function hasDraftBatch(\n ctx: ContentContext,\n entityIds: string[],\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<Set<string>> {\n validateLocale(locale)\n const result = new Set<string>()\n if (entityIds.length === 0) return result\n const client = await getDraftsClient(ctx)\n if (!client) return result\n\n const rows = await client.findMany({\n where: { entityId: { in: entityIds }, locale },\n })\n for (const row of rows) {\n result.add(row.entityId as string)\n }\n return result\n}\n\n/**\n * Compare the current draft with the live entity. Returns field-level\n * diffs between the published data and the draft (only for fields\n * present in the draft — missing fields are NOT \"changed to empty\").\n */\nexport async function compareDraftWithCurrent<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<{\n diffs: FieldDiff[]\n current: InferEntityDTO<F>\n draft: DraftEntry<InferUpdateInput<F>>\n} | null> {\n validateLocale(locale)\n const draft = await getDraft(ctx, entityId, locale)\n if (!draft) return null\n\n // Fetch the live entity with the same locale context as the draft.\n const config = getContentConfig()\n const defaultLocale = config.defaultLocale\n const findOptions =\n locale === DEFAULT_LOCALE_SENTINEL ? { defaultLocale } : { locale, defaultLocale }\n const current = await ctx.admin.findById(entityId, findOptions)\n if (!current) return null\n\n const fieldConfigs = ctx.entity.allFields as Record<string, FieldConfig> | undefined\n const currentRecord = current as Record<string, unknown>\n const draftRecord = draft.data as Record<string, unknown>\n const currentSubset: Record<string, unknown> = {}\n for (const key of Object.keys(draftRecord)) {\n currentSubset[key] = currentRecord[key]\n }\n const diffs = diffFields(currentSubset, draftRecord, fieldConfigs)\n for (const diff of diffs) {\n if (diff.type === 'blockTree') {\n // Normalize a null/undefined side to [] so add/clear of the whole field\n // (null ↔ blockTree[]) still produces a structural diff, not an opaque one.\n diff.blockDiffs = diffBlocks(\n Array.isArray(diff.from) ? diff.from : [],\n Array.isArray(diff.to) ? diff.to : [],\n )\n }\n }\n\n return { diffs, current, draft }\n}\n","/**\n * Per-locale publish status — independent draft/published state for\n * each locale of a publishable + translatable entity.\n *\n * Capability: requires `publishable() + at least one translatable\n * field` (the `_locale_status` table is registered only for that\n * combination). Reads silently return falsy on entities without it;\n * `setLocaleStatus` throws `EntityCapabilityError`.\n */\n\nimport 'server-only'\n\nimport type { FieldConfig } from '@murumets-ee/entity'\nimport type { InferUpdateInput } from '@murumets-ee/entity/admin'\nimport { EntityCapabilityError } from './errors.js'\nimport { type ContentContext, getLocaleStatusClient } from './internal/context.js'\nimport { upsertLocaleStatusRow } from './locale-status-slot.js'\nimport { validateLocale } from './locale-utils.js'\nimport { getContentConfig } from './plugin.js'\nimport type { LocalePublishStatus } from './types.js'\n\n/**\n * Get per-locale publish status overrides for an entity.\n * Missing locale = inherits the base entity status (no row written).\n *\n * **Not permission-gated, deliberately — see {@link getLocaleStatusBatch}.**\n */\nexport async function getLocaleStatus(\n ctx: ContentContext,\n entityId: string,\n): Promise<LocalePublishStatus[]> {\n const map = await getLocaleStatusBatch(ctx, [entityId])\n const entry = map.get(entityId)\n if (!entry) return []\n return Object.values(entry)\n}\n\n/**\n * Set per-locale publish status. Upserts into the locale_status\n * table — except when `locale === defaultLocale`, which updates the\n * base entity status column directly (the per-locale table only\n * stores overrides for non-default locales).\n *\n * **Both branches are publish-gated by the entity layer (D041).** The default\n * branch inherits it from `AdminClient.update`; the non-default branch routes\n * through `AdminClient.updateForLocale`, which asserts the SAME\n * `assertPublishAuthority` from the caller's payload before it hands the write\n * to the locale-status writer. This is deliberately a delegation and not a\n * second predicate in this package: `<entity>_locale_status` is the table the\n * public read predicate (`COALESCE(locale_status.status, main.status)`) resolves\n * against, so a direct `TableClient.upsert` here — which is what this function\n * used to do — is a fourth publish door, reachable from any plugin/route/job\n * holding a `ContentClient` (a PUBLIC subpath export) with no `publish` grant\n * ever consulted.\n */\nexport async function setLocaleStatus<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale: string,\n status: 'draft' | 'published',\n): Promise<void> {\n validateLocale(locale)\n const config = getContentConfig()\n\n // Default locale → update base entity status column.\n if (locale === config.defaultLocale) {\n const data: Record<string, unknown> = { status }\n if (status === 'published') data.publishedAt = new Date()\n await ctx.admin.update(entityId, data as InferUpdateInput<F>)\n return\n }\n\n const client = await getLocaleStatusClient(ctx)\n if (!client) {\n // Per-locale status only exists for publishable + translatable\n // entities. Calling on a non-translatable publishable (where the\n // only valid locale is the default) is a programmer error.\n // Checked BEFORE delegating: `updateForLocale` would otherwise fall back to\n // the base `status` column for a missing writer, silently publishing the\n // default locale instead of refusing.\n throw new EntityCapabilityError(ctx.entity.name, 'localeStatus')\n }\n\n // The writer we hand down is the RAW upsert, not this function — the\n // delegation terminates here rather than re-entering `updateForLocale`.\n //\n // Routing through `updateForLocale` rather than calling the upsert directly\n // is what closes the publish door: this branch used to write\n // `<entity>_locale_status` with no permission check at all, so any holder of\n // this public export could make a translation publicly live without\n // `publish`. `updateForLocale` asserts publish authority at the operation\n // entry (D041), so the gate is inherited rather than duplicated here.\n //\n // Widened through `Record<string, unknown>` for the same reason the\n // default-locale branch above does it: `InferUpdateInput<F>` is keyed on the\n // entity's own field map, which a generic `F` cannot be proven to overlap.\n const localeData: Record<string, unknown> = { status }\n await ctx.admin.updateForLocale(entityId, localeData as InferUpdateInput<F>, locale, {\n defaultLocale: config.defaultLocale,\n localeStatusWriter: (id, loc, s) => upsertLocaleStatusRow(client, id, loc, s),\n })\n}\n\n/**\n * Get per-locale publish status for multiple entities in one query.\n *\n * ## Why this read is NOT permission-gated (and what would gate it)\n *\n * It returns publish-state METADATA only — `{ locale, status, publishedAt }` —\n * never field data, so it is not a content-disclosure door the way the write\n * side above is a publish door. What it does expose is an existence oracle for\n * unpublished TRANSLATIONS: a principal without `view_unpublished` learns that\n * `et` is a draft, which `QueryClient` would have hidden. The correct predicate\n * is therefore `view_unpublished` (D017), NOT `publish`.\n *\n * A CodeRabbit pass proposed gating it on exactly that predicate. Deliberately\n * declined, on the strength of **F063**: `view_unpublished` governs `QueryClient`\n * reads — the PUBLIC delivery surface — and is not a disclosure boundary over\n * the admin API, where `AdminClient` shows editors their own drafts by design.\n * `ContentClient` is an in-process server-side API whose consumers are plugins,\n * routes and jobs on the admin side, so gating it here would extend the control\n * onto the surface F063 explicitly recommended NOT extending it to. The concrete\n * cost would be an editor lacking `view_unpublished` no longer able to see that\n * their OWN translation is still a draft.\n *\n * The asymmetry with the write side above is real, not convenient:\n * `setLocaleStatus` MINTS public visibility, so it is gated regardless of which\n * surface calls it. This read hands publish-state metadata to a caller who\n * already holds `view` on the row — they needed its id to ask.\n *\n * It is not applied here because the predicate (`mayViewUnpublishedEntity`) is\n * module-private to `@murumets-ee/entity` — re-deriving it in this package\n * would create exactly the second, drifting copy of a security predicate that\n * D041 exists to eliminate, and there is no read-path equivalent of\n * `updateForLocale` to delegate to. The one in-repo caller\n * (`admin-ui`'s versions route) is already gated by `checkPermission`. Closing\n * this properly means exporting the predicate from `@murumets-ee/entity` and\n * dropping non-`published` rows for principals without it — tracked as the\n * read-side sibling of F060.\n */\nexport async function getLocaleStatusBatch(\n ctx: ContentContext,\n entityIds: string[],\n): Promise<Map<string, Record<string, LocalePublishStatus>>> {\n const result = new Map<string, Record<string, LocalePublishStatus>>()\n if (entityIds.length === 0) return result\n const client = await getLocaleStatusClient(ctx)\n if (!client) return result\n\n const rows = await client.findMany({ where: { entityId: { in: entityIds } } })\n for (const r of rows) {\n const eid = r.entityId as string\n const locale = r.locale as string\n let entry = result.get(eid)\n if (!entry) {\n entry = {}\n result.set(eid, entry)\n }\n entry[locale] = {\n locale,\n status: r.status as 'draft' | 'published',\n publishedAt: (r.publishedAt as Date | null) ?? null,\n }\n }\n return result\n}\n","/**\n * Translation status reporting — per-locale completion of translatable\n * fields for one entity, batches of entities, or the whole entity type.\n *\n * Capability: requires the entity to have at least one translatable\n * field. All methods return falsy / empty when the entity has no\n * translatable fields (read-only and defensive).\n */\n\nimport 'server-only'\n\nimport { getContext, requireSiteFor } from '@murumets-ee/core'\nimport { schemaRegistry } from '@murumets-ee/db'\nimport { buildPartitionCondition, type FieldConfig } from '@murumets-ee/entity'\nimport { and, inArray } from 'drizzle-orm'\nimport { InvalidLocaleError } from './errors.js'\nimport type { ContentContext } from './internal/context.js'\nimport { getContentConfig } from './plugin.js'\nimport { getTranslationProvenanceBatch, translationFreshness } from './translation-provenance.js'\nimport type { TranslationReport, TranslationStatus } from './types.js'\n\n/**\n * The locales a status report covers and the default it skips: the request's\n * — which the admin narrows to its SITE's locales and default (plan `multisite`\n * phase 03) — else the configured content locales.\n */\nfunction statusLocales(): { locales: { code: string }[]; defaultLocale: string } {\n const config = getContentConfig()\n const ctx = getContext()\n const codes = ctx?.availableLocales ?? config.locales.map((l) => l.code)\n return {\n locales: codes.map((code) => ({ code })),\n defaultLocale: ctx?.defaultLocale ?? config.defaultLocale,\n }\n}\n\n/**\n * For one entity, compute per-locale completion status across every\n * translatable field. Default-locale rows are skipped.\n */\nfunction computeStatusForEntity(\n translatableFields: string[],\n translatedByLocale: Map<string, Record<string, unknown>> | undefined,\n locales: { code: string }[],\n defaultLocale: string,\n): TranslationStatus {\n const status: TranslationStatus = {}\n for (const locale of locales) {\n if (locale.code === defaultLocale) continue\n const translated = translatedByLocale?.get(locale.code) ?? {}\n const missing: string[] = []\n for (const fieldName of translatableFields) {\n if (translated[fieldName] === undefined || translated[fieldName] === null) {\n missing.push(fieldName)\n }\n }\n status[locale.code] = {\n complete: missing.length === 0,\n total: translatableFields.length,\n translated: translatableFields.length - missing.length,\n missing,\n }\n }\n return status\n}\n\n/**\n * Get translation status for an entity — per-locale completion report.\n */\nexport async function getTranslationStatus(\n ctx: ContentContext,\n entityId: string,\n): Promise<TranslationStatus> {\n // Single-entity is the batch path with one ID — keeps the two\n // codepaths from drifting.\n const map = await getTranslationStatusBatch(ctx, [entityId])\n return map.get(entityId) ?? {}\n}\n\n/**\n * Get translation status for multiple entities in a single query.\n * O(1) DB roundtrips regardless of `entityIds.length`.\n */\nexport async function getTranslationStatusBatch(\n ctx: ContentContext,\n entityIds: string[],\n): Promise<Map<string, TranslationStatus>> {\n const result = new Map<string, TranslationStatus>()\n if (entityIds.length === 0) return result\n\n const { locales, defaultLocale } = statusLocales()\n\n const translatableFields = Object.entries(ctx.entity.allFields as Record<string, FieldConfig>)\n .filter(([_, f]) => f.translatable)\n .map(([name]) => name)\n if (translatableFields.length === 0) return result\n\n // Translation tables are generated in @murumets-ee/entity (with FK\n // refs); accessed via schemaRegistry + direct Drizzle here.\n const translationTable = schemaRegistry.get(`${ctx.entity.name}_translations`)\n if (!translationTable) return result\n\n // A site-bound entity's translation rows are confined to the request's\n // site (multisite D003): ids alone are no boundary — a caller holding\n // another site's id must learn nothing about its translations.\n const site = await requireSiteFor(ctx.entity)\n const byIds = inArray(translationTable.entityId, entityIds)\n const translations = await ctx.db\n .select()\n .from(translationTable)\n .where(\n site !== undefined\n ? and(byIds, buildPartitionCondition(translationTable, { site }, ctx.entity.name))\n : byIds,\n )\n\n // Group: entityId → locale → { fieldName: value }\n const translationsByEntity = new Map<string, Map<string, Record<string, unknown>>>()\n for (const t of translations) {\n const row = t as Record<string, unknown>\n const eid = row.entityId as string\n const locale = row.locale as string\n const fieldValues: Record<string, unknown> = {}\n for (const fieldName of translatableFields) {\n fieldValues[fieldName] = row[fieldName]\n }\n let entry = translationsByEntity.get(eid)\n if (!entry) {\n entry = new Map()\n translationsByEntity.set(eid, entry)\n }\n entry.set(locale, fieldValues)\n }\n\n // What each locale was last saved from (agent-access D017) — one more query\n // for the whole batch, a comparison of stored hashes per locale after that.\n const provenance = await getTranslationProvenanceBatch(ctx.entity.name, entityIds, ctx.db)\n\n for (const entityId of entityIds) {\n const status = computeStatusForEntity(\n translatableFields,\n translationsByEntity.get(entityId),\n locales,\n defaultLocale,\n )\n const byLocale = provenance.get(entityId)\n for (const [locale, entry] of Object.entries(status)) {\n const freshness = translationFreshness(byLocale, locale)\n if (freshness) entry.freshness = freshness\n }\n result.set(entityId, status)\n }\n\n return result\n}\n\nconst EMPTY_REPORT: TranslationReport = {\n total: 0,\n complete: 0,\n partial: 0,\n missing: 0,\n outdated: 0,\n machineUnreviewed: 0,\n}\n\n/**\n * Roll up translation status across every entity of this type.\n *\n * Defaults to the first non-default configured locale; pass\n * `options.locale` to target a specific one. Returns counts of\n * complete / partial / missing entities for that locale.\n */\nexport async function getTranslationReport(\n ctx: ContentContext,\n options?: { locale?: string },\n): Promise<TranslationReport> {\n const { locales, defaultLocale } = statusLocales()\n const targetLocale = options?.locale ?? locales.find((l) => l.code !== defaultLocale)?.code\n if (!targetLocale) return { ...EMPTY_REPORT }\n // A locale the site does not serve has no report on that site.\n if (!locales.some((l) => l.code === targetLocale)) {\n throw new InvalidLocaleError(\n targetLocale,\n locales.map((l) => l.code),\n )\n }\n\n const entities = await ctx.admin.findMany()\n if (entities.length === 0) return { ...EMPTY_REPORT }\n\n // Single batched query covers every entity at once.\n const statusMap = await getTranslationStatusBatch(\n ctx,\n entities.map((e) => e.id),\n )\n\n let complete = 0\n let partial = 0\n let missing = 0\n let outdated = 0\n let machineUnreviewed = 0\n for (const entity of entities) {\n const status = statusMap.get(entity.id)\n const localeStatus = status?.[targetLocale]\n if (!localeStatus || localeStatus.translated === 0) missing++\n else if (localeStatus.complete) complete++\n else partial++\n // Independent of the three above: a draft translation is \"missing\" (not\n // live yet) and can be machine-unreviewed, or outdated, at the same time.\n if (localeStatus?.freshness?.outdated === true) outdated++\n if (localeStatus?.freshness?.machineUnreviewed === true) machineUnreviewed++\n }\n\n return { total: entities.length, complete, partial, missing, outdated, machineUnreviewed }\n}\n","/**\n * ContentClient — thin shell over per-feature modules.\n *\n * Wraps AdminClient with version history (`./versions.ts`), draft\n * overlays (`./drafts.ts`), translation status reporting\n * (`./translation-status.ts`), per-locale publish status\n * (`./locale-status.ts`), and block-layout operations (`./layout.ts`).\n *\n * The class is generic over the entity's `AllFields` map: when\n * constructed with a typed entity, every method's input/output is\n * inferred end-to-end. When constructed with a runtime `Entity`\n * (admin-ui's heterogeneous entity loops), the generic defaults to\n * `Record<string, FieldConfig>` and methods accept/return the loose\n * shape — same behavior as the pre-generic version.\n *\n * Usage:\n * import { createContentClient } from '@murumets-ee/content/client'\n * const pages = createContentClient(Page)\n * await pages.create({ title: 'Hello', layout: [...] })\n */\n\nimport 'server-only'\n\nimport { getApp, type Logger } from '@murumets-ee/core'\nimport { createAdminClient } from '@murumets-ee/core/clients'\nimport type { Entity, FieldConfig } from '@murumets-ee/entity'\nimport type {\n AdminClient,\n FindManyOptions,\n InferCreateInput,\n InferEntityDTO,\n InferUpdateInput,\n} from '@murumets-ee/entity/admin'\nimport { getVersionableOptions } from './behaviors/versionable.js'\nimport {\n compareDraftWithCurrent,\n countDrafts,\n deleteDraft,\n getDraft,\n hasDraft,\n hasDraftBatch,\n mergeDraft,\n publishDraft,\n saveDraft,\n} from './drafts.js'\nimport { type ContentContext, createContentContext } from './internal/context.js'\nimport { calculateDelta } from './internal/projection.js'\nimport { getLocaleStatus, getLocaleStatusBatch, setLocaleStatus } from './locale-status.js'\nimport {\n getTranslationReport,\n getTranslationStatus,\n getTranslationStatusBatch,\n} from './translation-status.js'\nimport {\n compareVersions,\n createVersionSnapshot,\n getVersion,\n getVersions,\n pruneVersions,\n restoreVersion,\n saveVersionSnapshot,\n writeVersionColumn,\n} from './versions.js'\n\nexport interface ContentClientConfig<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n admin: AdminClient<AllFields>\n entity: Entity<AllFields>\n logger?: Logger\n}\n\nexport class ContentClient<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n private ctx: ContentContext<AllFields>\n\n constructor(config: ContentClientConfig<AllFields>) {\n const versionableOptions = getVersionableOptions(config.entity.behaviors)\n this.ctx = createContentContext(config, versionableOptions)\n }\n\n // -----------------------------------------------------------------\n // CRUD (delegated to AdminClient + version snapshots)\n // -----------------------------------------------------------------\n\n async create(data: InferCreateInput<AllFields>): Promise<InferEntityDTO<AllFields>> {\n const result = await this.ctx.admin.create(data)\n if (this.ctx.versionableOptions) {\n await saveVersionSnapshot(this.ctx, result.id, result, null, false)\n }\n return result\n }\n\n findById(id: string, options?: { locale?: string }): Promise<InferEntityDTO<AllFields> | null> {\n return this.ctx.admin.findById(id, options)\n }\n\n findMany(options?: FindManyOptions): Promise<InferEntityDTO<AllFields>[]> {\n return this.ctx.admin.findMany(options)\n }\n\n /**\n * Base-row update + version snapshot. Subject to AdminClient's\n * cross-locale write guard (SD021): under a non-default request-context\n * locale, translatable fields throw `CrossLocaleWriteError` — that's\n * enforcement, not a gap. Locale-belonging writes go through the draft\n * flow (`saveDraft` → `publishDraft`) or `admin.updateForLocale` directly.\n */\n async update(id: string, data: InferUpdateInput<AllFields>): Promise<InferEntityDTO<AllFields>> {\n let previousState: InferEntityDTO<AllFields> | null = null\n if (this.ctx.versionableOptions) {\n previousState = await this.ctx.admin.findById(id)\n }\n\n const result = await this.ctx.admin.update(id, data)\n\n if (this.ctx.versionableOptions && previousState) {\n const delta = calculateDelta(previousState, result)\n const version = await saveVersionSnapshot(this.ctx, id, result, delta, false)\n if (version !== undefined) {\n await writeVersionColumn(this.ctx, id, version)\n await pruneVersions(this.ctx, id)\n return { ...result, _version: version } as InferEntityDTO<AllFields>\n }\n await pruneVersions(this.ctx, id)\n }\n\n return result\n }\n\n delete(id: string): Promise<unknown> {\n return this.ctx.admin.delete(id)\n }\n\n // -----------------------------------------------------------------\n // Translation delegation\n // -----------------------------------------------------------------\n\n saveTranslation(entityId: string, locale: string, translations: Record<string, unknown>) {\n return this.ctx.admin.saveTranslation(entityId, locale, translations)\n }\n\n deleteTranslation(entityId: string, locale?: string) {\n return this.ctx.admin.deleteTranslation(entityId, locale)\n }\n\n // -----------------------------------------------------------------\n // Version history\n // -----------------------------------------------------------------\n\n getVersions(entityId: string, options?: { limit?: number; offset?: number; locale?: string }) {\n return getVersions(this.ctx, entityId, options)\n }\n\n getVersion(entityId: string, version: number, locale?: string) {\n return getVersion(this.ctx, entityId, version, locale)\n }\n\n compareVersions(entityId: string, v1: number, v2: number, locale?: string) {\n return compareVersions(this.ctx, entityId, v1, v2, locale)\n }\n\n restoreVersion(entityId: string, version: number, locale?: string) {\n return restoreVersion(this.ctx, entityId, version, locale)\n }\n\n pruneVersions(entityId: string, locale?: string) {\n return pruneVersions(this.ctx, entityId, locale)\n }\n\n createVersionSnapshot(\n entityId: string,\n currentData: Record<string, unknown>,\n previousData?: Record<string, unknown> | null,\n locale?: string,\n user?: { id: string; name?: string },\n ) {\n return createVersionSnapshot(this.ctx, entityId, currentData, previousData, locale, user)\n }\n\n // -----------------------------------------------------------------\n // Translation status\n // -----------------------------------------------------------------\n\n getTranslationStatus(entityId: string) {\n return getTranslationStatus(this.ctx, entityId)\n }\n\n getTranslationStatusBatch(entityIds: string[]) {\n return getTranslationStatusBatch(this.ctx, entityIds)\n }\n\n getTranslationReport(options?: { locale?: string }) {\n return getTranslationReport(this.ctx, options)\n }\n\n // -----------------------------------------------------------------\n // Per-locale publish status\n // -----------------------------------------------------------------\n\n getLocaleStatus(entityId: string) {\n return getLocaleStatus(this.ctx, entityId)\n }\n\n setLocaleStatus(entityId: string, locale: string, status: 'draft' | 'published') {\n return setLocaleStatus(this.ctx, entityId, locale, status)\n }\n\n getLocaleStatusBatch(entityIds: string[]) {\n return getLocaleStatusBatch(this.ctx, entityIds)\n }\n\n // -----------------------------------------------------------------\n // Drafts\n // -----------------------------------------------------------------\n\n saveDraft(\n entityId: string,\n data: InferUpdateInput<AllFields>,\n locale?: string,\n user?: { id: string; name?: string },\n ) {\n return saveDraft(this.ctx, entityId, data, locale, user)\n }\n\n mergeDraft(\n entityId: string,\n patch: InferUpdateInput<AllFields>,\n locale?: string,\n user?: { id: string; name?: string },\n ) {\n return mergeDraft(this.ctx, entityId, patch, locale, user)\n }\n\n getDraft(entityId: string, locale?: string) {\n return getDraft(this.ctx, entityId, locale)\n }\n\n deleteDraft(entityId: string, locale?: string) {\n return deleteDraft(this.ctx, entityId, locale)\n }\n\n publishDraft(entityId: string, locale?: string, user?: { id: string; name?: string }) {\n return publishDraft(this.ctx, entityId, locale, user)\n }\n\n hasDraft(entityId: string, locale?: string) {\n return hasDraft(this.ctx, entityId, locale)\n }\n\n countDrafts(locale?: string) {\n return countDrafts(this.ctx, locale)\n }\n\n hasDraftBatch(entityIds: string[], locale?: string) {\n return hasDraftBatch(this.ctx, entityIds, locale)\n }\n\n compareDraftWithCurrent(entityId: string, locale?: string) {\n return compareDraftWithCurrent(this.ctx, entityId, locale)\n }\n}\n\n/**\n * Factory — creates a ContentClient for an entity. Must be called\n * after `createApp()`. Generic flows from the entity definition:\n * `createContentClient(Article)` returns a `ContentClient<typeof\n * Article['allFields']>` typed end-to-end.\n */\nexport function createContentClient<AllFields extends Record<string, FieldConfig>>(\n entity: Entity<AllFields>,\n): ContentClient<AllFields> {\n const admin = createAdminClient(entity)\n return new ContentClient<AllFields>({\n admin,\n entity,\n logger: getApp().logger.child({ content: entity.name }),\n })\n}\n"],"mappings":"q1BAgCA,SAAS,EAAa,EAA2B,CAC/C,MAAO,CACL,GAAI,EAAI,GACR,SAAU,EAAI,SACd,OAAQ,EAAI,OACZ,KAAM,EAAI,KACV,UAAW,EAAI,UACf,cAAe,EAAI,eAAiB,KACpC,UAAW,EAAI,UACf,UAAW,EAAI,SACjB,CACF,CAOA,eAAe,EACb,EACA,EACA,EAC8C,CAC9C,GAAI,CAKF,OAAQ,MAJU,EAAI,MAAM,SAC1B,EACA,IAAA,IAAqC,CAAC,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Q,CAAI,CACtD,CAEA,SAAS,EAAkB,EAAiB,CAC1C,OAAO,EAAS,KAAK,IAAK,EAAU,CAAM,CAC5C,CAEA,YAAY,EAAiB,CAC3B,OAAO,EAAY,KAAK,IAAK,CAAM,CACrC,CAEA,cAAc,EAAqB,EAAiB,CAClD,OAAO,EAAc,KAAK,IAAK,EAAW,CAAM,CAClD,CAEA,wBAAwB,EAAkB,EAAiB,CACzD,OAAO,EAAwB,KAAK,IAAK,EAAU,CAAM,CAC3D,CACF,EAQA,SAAgB,GACd,EAC0B,CAE1B,OAAO,IAAI,EAAyB,CAClC,MAFY,EAAkB,CAE1B,EACJ,SACA,OAAQ,EAAO,CAAC,CAAC,OAAO,MAAM,CAAE,QAAS,EAAO,IAAK,CAAC,CACxD,CAAC,CACH"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-DK3Fl9T5.mjs";import{h as t}from"./translation-provenance-eqhsGAyi.mjs";import{requireSiteFor as n}from"@murumets-ee/core";import"server-only";var r=e({createContentContext:()=>i,getDraftsClient:()=>a,getLocaleStatusClient:()=>s,getVersionsClient:()=>o});function i(e,t){return{entity:e.entity,admin:e.admin,db:e.admin.getDb(),versionableOptions:t,logger:e.logger}}async function a(e){let{drafts:r}=t(e.entity.name);return r?r.makeClient(e.db,await n(e.entity)):null}async function o(e){let{versions:r}=t(e.entity.name);return r?r.makeClient(e.db,await n(e.entity)):null}async function s(e){let{localeStatus:r}=t(e.entity.name);return r?r.makeClient(e.db,await n(e.entity)):null}export{o as a,s as i,i as n,a as r,r as t};
|
|
2
|
+
//# sourceMappingURL=context-DtHgyrgb.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-
|
|
1
|
+
{"version":3,"file":"context-DtHgyrgb.mjs","names":[],"sources":["../src/internal/context.ts"],"sourcesContent":["/**\n * Shared per-instance state for ContentClient feature modules.\n *\n * The package's domain modules (`versions.ts`, `drafts.ts`,\n * `translation-status.ts`, `locale-status.ts`, `layout.ts`) are written\n * as free functions that take a `ContentContext` as their first\n * argument. ContentClient itself is a thin shell that builds the\n * context once and forwards every public method to the corresponding\n * free function.\n *\n * Why free functions instead of one class with everything inline:\n * - 1000+ LoC in one class is impossible to navigate and audit.\n * - Each module has clear inputs (the context + method args) and no\n * hidden dependencies on private state.\n * - Splits cleanly along the same boundaries as the per-entity\n * capability tables (drafts, versions, locale_status, ...) — every\n * module owns exactly one capability surface.\n */\n\nimport 'server-only'\n\nimport { type Logger, requireSiteFor } from '@murumets-ee/core'\nimport type { Entity, FieldConfig } from '@murumets-ee/entity'\nimport type { AdminClient } from '@murumets-ee/entity/admin'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { getVersionableOptions } from '../behaviors/versionable.js'\nimport { getContentTables } from '../schema/registry.js'\n\n/**\n * Per-instance content context. Built once in `createContentContext()`\n * and threaded through every domain module's free functions.\n */\nexport interface ContentContext<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n entity: Entity<AllFields>\n admin: AdminClient<AllFields>\n db: PostgresJsDatabase\n versionableOptions: ReturnType<typeof getVersionableOptions>\n logger?: Logger | undefined\n}\n\n/**\n * Build a content context from an AdminClient + entity. The DB handle\n * is read off the AdminClient (it owns the read-write connection).\n */\nexport function createContentContext<AllFields extends Record<string, FieldConfig>>(\n config: {\n admin: AdminClient<AllFields>\n entity: Entity<AllFields>\n logger?: Logger\n },\n // Lazy import to avoid a static cycle: behaviors/versionable.ts is loaded\n // by client.ts which would otherwise close the loop. Phase-2 validated\n // the static import graph; this is a private helper bundled into the\n // same chunk so the dynamic-vs-static rule doesn't apply.\n versionableOptions: ReturnType<typeof getVersionableOptions>,\n): ContentContext<AllFields> {\n return {\n entity: config.entity,\n admin: config.admin,\n db: config.admin.getDb(),\n versionableOptions,\n logger: config.logger,\n }\n}\n\n// -------------------------------------------------------------------\n// Per-capability TableClient lookups. For a site-bound entity the client\n// is CONFINED to the request's site (multisite D003) — `requireSiteFor`\n// throws when there is none, so a companion read can never widen to every\n// site. Async for that reason: the single-site answer may need a lookup.\n// Each returns null if the entity\n// hasn't registered the corresponding table (i.e. doesn't have the\n// behavior). ContentClient public methods translate that null into\n// either a thrown EntityCapabilityError (writes) or a falsy return\n// (reads).\n// -------------------------------------------------------------------\n\nexport async function getDraftsClient(ctx: ContentContext) {\n const { drafts } = getContentTables(ctx.entity.name)\n return drafts ? drafts.makeClient(ctx.db, await requireSiteFor(ctx.entity)) : null\n}\n\nexport async function getVersionsClient(ctx: ContentContext) {\n const { versions } = getContentTables(ctx.entity.name)\n return versions ? versions.makeClient(ctx.db, await requireSiteFor(ctx.entity)) : null\n}\n\nexport async function getLocaleStatusClient(ctx: ContentContext) {\n const { localeStatus } = getContentTables(ctx.entity.name)\n return localeStatus ? localeStatus.makeClient(ctx.db, await requireSiteFor(ctx.entity)) : null\n}\n"],"mappings":"qSA8CA,SAAgB,EACd,EASA,EAC2B,CAC3B,MAAO,CACL,OAAQ,EAAO,OACf,MAAO,EAAO,MACd,GAAI,EAAO,MAAM,MAAM,EACvB,qBACA,OAAQ,EAAO,MACjB,CACF,CAcA,eAAsB,EAAgB,EAAqB,CACzD,GAAM,CAAE,UAAW,EAAiB,EAAI,OAAO,IAAI,EACnD,OAAO,EAAS,EAAO,WAAW,EAAI,GAAI,MAAM,EAAe,EAAI,MAAM,CAAC,EAAI,IAChF,CAEA,eAAsB,EAAkB,EAAqB,CAC3D,GAAM,CAAE,YAAa,EAAiB,EAAI,OAAO,IAAI,EACrD,OAAO,EAAW,EAAS,WAAW,EAAI,GAAI,MAAM,EAAe,EAAI,MAAM,CAAC,EAAI,IACpF,CAEA,eAAsB,EAAsB,EAAqB,CAC/D,GAAM,CAAE,gBAAiB,EAAiB,EAAI,OAAO,IAAI,EACzD,OAAO,EAAe,EAAa,WAAW,EAAI,GAAI,MAAM,EAAe,EAAI,MAAM,CAAC,EAAI,IAC5F"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-DK3Fl9T5.mjs";import{getAppOrUndefined as t,getContext as n,requireSiteFor as r}from"@murumets-ee/core";var i=e({siteForDocumentType:()=>a});async function a(e){let i=n()?.app??t();if(!i)return;let a=i.entities.get(e);if(a)return r(a,i)}export{a as n,i as t};
|
|
2
|
+
//# sourceMappingURL=document-site-B8tmEqLw.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"document-site-B8tmEqLw.mjs","names":[],"sources":["../src/internal/document-site.ts"],"sourcesContent":["/**\n * The site a document-type-keyed companion access acts on (plan `multisite`\n * D003) — for the stores the block editor calls with a bare `documentType`\n * string rather than an entity object (`document-draft-store.ts`,\n * `document-version-store.ts`).\n *\n * `undefined` for a shared entity, or a type this app does not know (its\n * content tables are not registered either, so nothing is read). Throws\n * `SiteRequiredError` for a bound entity with no site in the request.\n */\n\nimport { getAppOrUndefined, getContext, requireSiteFor } from '@murumets-ee/core'\n\nexport async function siteForDocumentType(documentType: string): Promise<string | undefined> {\n // No booted app (a unit harness): there is no entity to consult, and a\n // bound type's partitioned table then refuses to build an unconfined client\n // — so returning `undefined` here cannot widen anything.\n const app = getContext()?.app ?? getAppOrUndefined()\n if (!app) return undefined\n const entity = app.entities.get(documentType)\n if (!entity) return undefined\n return requireSiteFor(entity, app)\n}\n"],"mappings":"mLAaA,eAAsB,EAAoB,EAAmD,CAI3F,IAAM,EAAM,EAAW,CAAC,EAAE,KAAO,EAAkB,EACnD,GAAI,CAAC,EAAK,OACV,IAAM,EAAS,EAAI,SAAS,IAAI,CAAY,EACvC,KACL,OAAO,EAAe,EAAQ,CAAG,CACnC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as VersionableFields } from "../versionable-
|
|
2
|
-
import { a as siteChromeEntity, i as SiteChromeEntityOptions, n as CHROME_PLACEMENT_LABELS, r as ChromePlacement, t as CHROME_PLACEMENTS } from "../site-chrome-
|
|
1
|
+
import { t as VersionableFields } from "../versionable-D2JjselN.mjs";
|
|
2
|
+
import { a as siteChromeEntity, i as SiteChromeEntityOptions, n as CHROME_PLACEMENT_LABELS, r as ChromePlacement, t as CHROME_PLACEMENTS } from "../site-chrome-BiV3zhw0.mjs";
|
|
3
3
|
import { Behavior, Entity, EntityAdminConfig, ForbiddenError } from "@murumets-ee/entity";
|
|
4
4
|
|
|
5
5
|
//#region src/entities/detail-template.d.ts
|
package/dist/entities/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"../versionable-Br_G5VGR.mjs";import{t}from"../detail-template-names-CD1Y9n1U.mjs";import{n,r,t as i}from"../site-chrome-
|
|
1
|
+
import{n as e}from"../versionable-Br_G5VGR.mjs";import{t}from"../detail-template-names-CD1Y9n1U.mjs";import{n,r,t as i}from"../site-chrome-BAtQaAqC.mjs";import{ForbiddenError as a,auditable as o,defineEntity as s,field as c,isTemplateDrawn as l,publishable as u}from"@murumets-ee/entity";const d={label:{label:`Name`,description:`Shown in the admin list and as the editor title. Visitors never see it.`}};function f(e){let t={...d};for(let[n,r]of Object.entries(e??{}))t[n]={...t[n],...r};return t}var p=class extends a{constructor(){super(`A detail template is not deleted: the rows it draws are still on the site. Unpublish it instead — those pages then show a plain fallback, and the draft stays editable.`),this.name=`DetailTemplateDeleteRefusedError`}};const m={name:`content:detail-template-undeletable`,hooks:{beforeDelete:async()=>{throw new p}}};function h(e){let t=[];for(let n of e){if(!l(n))throw Error(`detailTemplateEntity: '${n.name}' is listed in \`for\` but does not declare \`frontend: { path, drawnBy: 'template' }\`. A template for it would never be drawn.`);t.includes(n.name)||t.push(n.name)}return t}function g(n){let r=n.viewRole??`editor`,i=n.updateRole??`editor`,a=n.adminRole??`admin`,l=h(n.for);return s({name:t,site:`bound`,kind:`collection`,fields:{target:c.select({options:l,required:!0,unique:!0}),label:c.text({required:!0}),layout:c.blockTree({translatable:!0,rowsFrom:`target`,...n.environment!==void 0&&{environment:n.environment}})},behaviors:[o(),u(),e({maxPerDoc:n.maxVersions??30}),m,...n.behaviors??[]],scope:`global`,access:{view:r,create:a,update:i,delete:a},admin:{icon:`layout-template`,description:`One page layout per kind of synced record, drawn for every record of that kind.`,rootFields:[`label`],fieldOverrides:f(n.admin?.fieldOverrides),titleField:`label`,group:`Site`,disableCreate:!0,...l.length===0&&{hidden:!0}}})}export{i as CHROME_PLACEMENTS,n as CHROME_PLACEMENT_LABELS,p as DetailTemplateDeleteRefusedError,g as detailTemplateEntity,h as detailTemplateTargets,r as siteChromeEntity};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { o as LocaleEntry, r as I18nConfig } from "./types-
|
|
1
|
+
import { o as LocaleEntry, r as I18nConfig } from "./types-wMTglM4j.mjs";
|
|
2
2
|
import { Behavior, DateField, Entity, JsonField, SelectField, TextField } from "@murumets-ee/entity";
|
|
3
3
|
import { ToolkitApp } from "@murumets-ee/core";
|
|
4
4
|
import { MessageEntry } from "@murumets-ee/i18n";
|
|
@@ -272,4 +272,4 @@ declare function resolveSiteI18n(app: ToolkitApp, options?: {
|
|
|
272
272
|
declare function resolveMessageOverrides(app: ToolkitApp, locale: string): Promise<MessageEntry[]>;
|
|
273
273
|
//#endregion
|
|
274
274
|
export { withOverrides as A, WorkflowableFields as C, OverridesMap as D, OverrideDirective as E, WithOverridesFields as O, WorkflowTransitionError as S, workflowable as T, EntityCapability as _, resolveI18nConfig as a, WORKFLOW_TRANSITIONS as b, DraftNotFoundError as c, VersionNotFoundError as d, BlockDiffEntry as f, PropDiff as g, FieldDiff as h, resolveEffectiveLocales as i, hasWithOverrides as k, EntityCapabilityError as l, DiffSegment as m, SiteI18n as n, resolveSiteI18n as o, BlockDiffStatus as p, enabledLocaleCodes as r, resolveSiteLocales as s, resolveMessageOverrides as t, InvalidLocaleError as u, entitySupports as v, isAllowedTransition as w, WorkflowState as x, WORKFLOW_STATES as y };
|
|
275
|
-
//# sourceMappingURL=index-
|
|
275
|
+
//# sourceMappingURL=index-Bni-PiIz.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-
|
|
1
|
+
{"version":3,"file":"index-Bni-PiIz.d.mts","names":[],"sources":["../src/behaviors/with-overrides.ts","../src/behaviors/workflowable.ts","../src/capabilities.ts","../src/diff/types.ts","../src/errors.ts","../src/locale-registry.ts","../src/message-registry.ts"],"mappings":";;;;;;;;;;;KAqDK,iBAAA;EACC,IAAA;AAAA;EAEA,IAAA;EACA,KAAA,GAAQ,MAAA;EACR,MAAA,GAAS,MAAA,SAAe,MAAA;AAAA;EAExB,IAAA;EAAiB,KAAA,EAAO,MAAA;AAAA;AAAA,KAEzB,YAAA,GAAe,MAAM,SAAS,iBAAA;AAAA,KAEvB,mBAAA;EAcV,UAAA,EAAY,SAAS;AAAA;;;AC/B4B;AASnD;iBD4LgB,aAAA,CAAA,GAAiB,QAAQ,CAAC,mBAAA;;;;;;iBAmD1B,gBAAA,CACd,SAAA,EAAW,aAAa;EAAG,IAAA;AAAA,IAAiB,MAAA;;;cC1PjC,eAAA;AAAA,KACD,aAAA,WAAwB,eAAe;ADqMnD;;;;AAA6D;AAmD7D;;AAnDA,cC5La,oBAAA;EAAA;;;;;;ADgPqE;;;AAAA,iBCrOlE,mBAAA,CAAoB,IAAA,EAAM,aAAA,EAAe,EAAA,EAAI,aAAa;AArB1E;;;;AAAA,cA+Ba,uBAAA,SAAgC,KAAA;EAAA,SAClC,IAAA,EAAM,aAAA;EAAA,SACN,EAAA,EAAI,aAAA;cAED,IAAA,EAAM,aAAA,EAAe,EAAA,EAAI,aAAA;AAAA;AAAA,KAW3B,kBAAA;EACV,eAAA,EAAiB,WAAA;IAAgB,QAAA;EAAA;EACjC,iBAAA,EAAmB,SAAA;EACnB,aAAA,EAAe,SAAA;EACf,kBAAA,EAAoB,SAAA;AAAA;AAAA,iBAGN,YAAA,CAAA,GAAgB,QAAQ,CAAC,kBAAA;;;KC7E7B,gBAAA;;;;;;iBA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AA;ALlEX;AAAA,UK2GiB,QAAA;;EAEf,IAAA;EL/FqB;EKiGrB,OAAA,EAAS,WAAA;ELqEkB;;;AAAgC;AAmD7D;;;;;;EK7GE,IAAA,EAAM,UAAA;EL8GN;EK5GA,OAAA,EAAS,UAAA;AAAA;;;;AJ9IX;;iBIwKsB,kBAAA,CACpB,GAAA,EAAK,UAAA,EACL,OAAA;EAAW,IAAA;EAAe,OAAA,YAAmB,WAAA;AAAA,IAC5C,OAAA;EAAU,IAAA;EAA0B,OAAA,EAAS,WAAA;AAAA;AJ1KG;AASnD;;;;;;;;;;;AAWA;;;;;AApBmD,iBIkM7B,eAAA,CACpB,GAAA,EAAK,UAAA,EACL,OAAA;EAAW,IAAA;EAAe,OAAA,YAAmB,WAAA;AAAA,IAC5C,OAAA,CAAQ,QAAA;;;;;;;;iBCrMW,uBAAA,CACpB,GAAA,EAAK,UAAA,EACL,MAAA,WACC,OAAA,CAAQ,YAAA"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as LocaleDirection, c as LockInfo, d as TranslationReport, f as TranslationStatus, i as LocaleConfig, l as RoutingStrategy, m as VersionableOptions, n as DraftEntry, o as LocaleEntry, p as VersionEntry, r as I18nConfig, t as ContentConfig, u as TranslationFieldStatus } from "./types-
|
|
2
|
-
import { n as getVersionableOptions, r as versionable } from "./versionable-
|
|
3
|
-
import { A as withOverrides, C as WorkflowableFields, D as OverridesMap, E as OverrideDirective, O as WithOverridesFields, S as WorkflowTransitionError, T as workflowable, _ as EntityCapability, a as resolveI18nConfig, b as WORKFLOW_TRANSITIONS, c as DraftNotFoundError, d as VersionNotFoundError, f as BlockDiffEntry, g as PropDiff, h as FieldDiff, i as resolveEffectiveLocales, k as hasWithOverrides, l as EntityCapabilityError, m as DiffSegment, n as SiteI18n, o as resolveSiteI18n, p as BlockDiffStatus, r as enabledLocaleCodes, s as resolveSiteLocales, t as resolveMessageOverrides, u as InvalidLocaleError, v as entitySupports, w as isAllowedTransition, x as WorkflowState, y as WORKFLOW_STATES } from "./index-
|
|
4
|
-
import { a as ROUTING_STRATEGIES, i as Locale, n as prefixDefaultLocaleForStrategy, o as i18nSettings, r as Message, t as localePrefixForStrategy } from "./routing-strategy-
|
|
1
|
+
import { a as LocaleDirection, c as LockInfo, d as TranslationReport, f as TranslationStatus, i as LocaleConfig, l as RoutingStrategy, m as VersionableOptions, n as DraftEntry, o as LocaleEntry, p as VersionEntry, r as I18nConfig, t as ContentConfig, u as TranslationFieldStatus } from "./types-wMTglM4j.mjs";
|
|
2
|
+
import { n as getVersionableOptions, r as versionable } from "./versionable-D2JjselN.mjs";
|
|
3
|
+
import { A as withOverrides, C as WorkflowableFields, D as OverridesMap, E as OverrideDirective, O as WithOverridesFields, S as WorkflowTransitionError, T as workflowable, _ as EntityCapability, a as resolveI18nConfig, b as WORKFLOW_TRANSITIONS, c as DraftNotFoundError, d as VersionNotFoundError, f as BlockDiffEntry, g as PropDiff, h as FieldDiff, i as resolveEffectiveLocales, k as hasWithOverrides, l as EntityCapabilityError, m as DiffSegment, n as SiteI18n, o as resolveSiteI18n, p as BlockDiffStatus, r as enabledLocaleCodes, s as resolveSiteLocales, t as resolveMessageOverrides, u as InvalidLocaleError, v as entitySupports, w as isAllowedTransition, x as WorkflowState, y as WORKFLOW_STATES } from "./index-Bni-PiIz.mjs";
|
|
4
|
+
import { a as ROUTING_STRATEGIES, i as Locale, n as prefixDefaultLocaleForStrategy, o as i18nSettings, r as Message, t as localePrefixForStrategy } from "./routing-strategy-DVWB7qPp.mjs";
|
|
5
5
|
export { type BlockDiffEntry, type BlockDiffStatus, type ContentConfig, type DiffSegment, type DraftEntry, DraftNotFoundError, type EntityCapability, EntityCapabilityError, type FieldDiff, type I18nConfig, InvalidLocaleError, Locale, type LocaleConfig, type LocaleDirection, type LocaleEntry, type LockInfo, Message, type OverrideDirective, type OverridesMap, type PropDiff, ROUTING_STRATEGIES, type RoutingStrategy, type SiteI18n, type TranslationFieldStatus, type TranslationReport, type TranslationStatus, type VersionEntry, VersionNotFoundError, type VersionableOptions, WORKFLOW_STATES, WORKFLOW_TRANSITIONS, type WithOverridesFields, type WorkflowState, WorkflowTransitionError, type WorkflowableFields, enabledLocaleCodes, entitySupports, getVersionableOptions, hasWithOverrides, i18nSettings, isAllowedTransition, localePrefixForStrategy, prefixDefaultLocaleForStrategy, resolveEffectiveLocales, resolveI18nConfig, resolveMessageOverrides, resolveSiteI18n, resolveSiteLocales, versionable, withOverrides, workflowable };
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e,t}from"./versionable-Br_G5VGR.mjs";import{i as n,n as r,r as i,t as a}from"./errors-NRNILhhm.mjs";import{n as o,r as s,t as c}from"./locale-entity-CoSq3C77.mjs";import{a as l,i as u,
|
|
1
|
+
import{n as e,t}from"./versionable-Br_G5VGR.mjs";import{i as n,n as r,r as i,t as a}from"./errors-NRNILhhm.mjs";import{n as o,r as s,t as c}from"./locale-entity-CoSq3C77.mjs";import{a as l,i as u,o as d,r as f,t as p}from"./locale-registry-COsJrVZl.mjs";import{n as m,r as h,t as g}from"./routing-strategy-D6B4ngT9.mjs";import{USER_ID_MAX_LENGTH as _,field as v}from"@murumets-ee/entity";import{createSystemReachResolver as y}from"@murumets-ee/core";import{QueryClient as b}from"@murumets-ee/entity/query";import{schemaRegistry as x}from"@murumets-ee/db";import{eq as S}from"drizzle-orm";const C=new Set([`hide`,`patch`,`replace`]),w=Symbol.for(`@murumets-ee/content:withOverrides`),T=new Set([`__proto__`,`constructor`,`prototype`]);function E(e,t,n=0){if(e!=null&&!(typeof e!=`object`||Array.isArray(e)))for(let r of Object.keys(e)){if(T.has(r))throw Error(`withOverrides: reserved key '${r}' at ${t} is not allowed.`);n<3&&E(e[r],`${t}.${r}`,n+1)}}function D(e){if(e==null)return{};if(typeof e!=`object`||Array.isArray(e))throw Error(`withOverrides: _overrides must be a plain object map.`);let t=e,n=Object.keys(t);if(n.length>100)throw Error(`withOverrides: _overrides has ${n.length} entries; cap is 100.`);let r={};for(let e of n){if(T.has(e))throw Error(`withOverrides: reserved key '${e}' is not allowed.`);let n=t[e];if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`withOverrides: _overrides['${e}'] must be a directive object.`);let i=n.kind;if(typeof i!=`string`||!C.has(i))throw Error(`withOverrides: _overrides['${e}'].kind must be one of [hide, patch, replace]; got ${String(i)}.`);if(i===`patch`){let t=n;O(t.props,`_overrides['${e}'].props`),O(t.traits,`_overrides['${e}'].traits`)}if(i===`replace`){let t=n.block;if(typeof t!=`object`||!t||Array.isArray(t)||typeof t.id!=`string`)throw Error(`withOverrides: _overrides['${e}'] replace payload must include an object 'block' with a string 'id'.`)}E(n,`_overrides['${e}']`),r[e]=n}return r}function O(e,t){if(e!==void 0&&(typeof e!=`object`||!e||Array.isArray(e)))throw Error(`withOverrides: ${t} must be an object.`)}function k(){return{name:`withOverrides`,fields:{_overrides:v.json({default:()=>({}),internal:!0,refScan:!0})},hooks:{beforeCreate:async e=>(e._overrides===void 0?e._overrides={}:e._overrides=D(e._overrides),e),beforeUpdate:async(e,t)=>(t._overrides===void 0||(t._overrides=D(t._overrides)),t)},[w]:!0}}function A(e){return e?e.some(e=>!!e?.[w]):!1}const j=[`draft`,`in_review`,`approved`,`rejected`,`published`],M={draft:[`in_review`],in_review:[`approved`,`rejected`],approved:[`published`,`in_review`],rejected:[`in_review`,`draft`],published:[`draft`]};function N(e,t){return e===t?!0:M[e]?.includes(t)??!1}var P=class extends Error{from;to;constructor(e,t){super(`Invalid workflow transition: ${e} → ${t}. Allowed transitions from "${e}": [${(M[e]??[]).join(`, `)}].`),this.name=`WorkflowTransitionError`,this.from=e,this.to=t}};function F(){return{name:`workflowable`,fields:{_workflowStatus:v.select({options:j,default:`draft`,indexed:!0,required:!0,internal:!0}),_workflowAssignee:v.text({required:!1,internal:!0,maxLength:_}),_workflowNote:v.text({required:!1,internal:!0}),_workflowUpdatedAt:v.date({internal:!0})},hooks:{beforeCreate:async e=>(e._workflowStatus=`draft`,e._workflowUpdatedAt=new Date,e),beforeUpdate:async(e,t,n)=>{let r=t._workflowStatus;if(r===void 0)return t;if(!j.includes(r))throw new P(`draft`,r);let i=(await n?.loadCurrent?.())?._workflowStatus??`draft`,a=r;if(!N(i,a))throw new P(i,a);return t._workflowUpdatedAt=new Date,t}}}}function I(e,t){switch(t){case`drafts`:return L(e,`publishable`);case`versions`:return L(e,`versionable`);case`localeStatus`:return L(e,`publishable`)&&R(e);case`translations`:return R(e)}}function L(e,t){return e.behaviors?.some(e=>e.name===t)??!1}function R(e){let t=e.allFields;for(let e of Object.keys(t)){let n=t[e];if(n&&n.translatable===!0)return!0}return!1}const z=y(`message-registry`),B=2e4;async function V(e,t){if(!e.entities?.has(`message`))return[];let n=x.get(`message`);if(!n)return[];let r=new b({entity:h,db:e.db.readOnly,logger:e.logger.child({registry:`message`}),contextResolver:z});try{let i=await r.findMany({where:S(n.locale,t),limit:B});return i.length>=B&&e.logger.warn({locale:t,cap:B},`message override read hit the row cap — some overrides were not applied`),i.map(e=>{let t=e;return{namespace:String(t.namespace),key:String(t.key),value:String(t.value)}})}catch(n){return e.logger.warn({err:n,locale:t},`message registry read failed — falling back to shipped defaults only`),[]}}export{a as DraftNotFoundError,r as EntityCapabilityError,i as InvalidLocaleError,c as Locale,h as Message,o as ROUTING_STRATEGIES,n as VersionNotFoundError,j as WORKFLOW_STATES,M as WORKFLOW_TRANSITIONS,P as WorkflowTransitionError,p as enabledLocaleCodes,I as entitySupports,t as getVersionableOptions,A as hasWithOverrides,s as i18nSettings,N as isAllowedTransition,g as localePrefixForStrategy,m as prefixDefaultLocaleForStrategy,f as resolveEffectiveLocales,u as resolveI18nConfig,V as resolveMessageOverrides,l as resolveSiteI18n,d as resolveSiteLocales,e as versionable,k as withOverrides,F as workflowable};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-DK3Fl9T5.mjs";import{n as t,r as n,t as r}from"./locale-entity-CoSq3C77.mjs";import{t as i}from"./content-config-store-8omQF5p5.mjs";import{createSystemReachResolver as a,getApp as o,getCurrentSite as s,mergeConfigOverrides as c,readSiteRecord as l,resolveImplicitSite as u}from"@murumets-ee/core";import{QueryClient as d}from"@murumets-ee/entity/query";var f=e({enabledLocaleCodes:()=>v,resolveEffectiveLocales:()=>_,resolveI18nConfig:()=>y,resolveInstallBaseLocale:()=>T,resolveSiteI18n:()=>w,resolveSiteLocales:()=>C});const p=a(`locale-registry`);function m(){return i().locales.map((e,t)=>({code:e.code,label:e.label,enabled:!0,direction:`ltr`,sortOrder:t}))}function h(e,t){return e.sortOrder-t.sortOrder||e.code.localeCompare(t.code)}async function g(e){return e.entities?.has(`locale`)?(await new d({entity:r,db:e.db.readOnly,logger:e.logger.child({registry:`locale`}),contextResolver:p}).findMany({limit:1e3})).map(e=>{let t=e;return{code:String(t.code),label:typeof t.label==`string`&&t.label.length>0?t.label:String(t.code),enabled:t.enabled!==!1,direction:t.direction===`rtl`?`rtl`:`ltr`,sortOrder:typeof t.sortOrder==`number`?t.sortOrder:0}}):[]}async function _(e){let t;try{t=await g(e)}catch(t){return e.logger.warn({err:t},`locale registry read failed — falling back to content() defaults`),[...m()].sort(h)}return c({defaults:m(),overrides:t,idOfDefault:e=>e.code,idOfOverride:e=>e.code}).sort(h)}function v(e){return e.filter(e=>e.enabled).map(e=>e.code)}async function y(e,r){let a=v(r??await _(e)),o=i().defaultLocale,s={};try{let{createSettingsClient:t}=await import(`@murumets-ee/settings/runtime`);s=await t(n,{app:e}).getAll()??{}}catch(t){e.logger.warn({err:t},`i18n settings read failed — falling back to content() defaults`)}let c=typeof s.defaultLocale==`string`&&s.defaultLocale.length>0?s.defaultLocale:o,l=a.includes(c)?c:a.includes(o)?o:a[0]??o,u=s.routingStrategy;return{defaultLocale:l,routingStrategy:t.includes(typeof u==`string`?u:``)?u:`no-prefix-default`}}async function b(e,t){return t??s()??await u(e).catch(()=>void 0)}function x(e,t){return l(e,t)}function S(e,t){let n=t?.locales??[];return n.length===0?e:e.filter(e=>n.includes(e.code))}async function C(e,t={}){let n=[...t.entries??await _(e)],r=await b(e,t.site);return r===void 0?{site:r,entries:n}:{site:r,entries:S(n,await x(e,r))}}async function w(e,n={}){let r=[...n.entries??await _(e)],i=await y(e,r),a=await b(e,n.site);if(a===void 0)return{site:a,entries:r,i18n:i,install:i};let o=await x(e,a),s=S(r,o),c=v(s),l=e.config.sites?.multiple===!0,u=l?o?.defaultLocale:void 0,d=u!==void 0&&c.includes(u)?u:c.includes(i.defaultLocale)?i.defaultLocale:c[0]??i.defaultLocale,f=l?o?.routingStrategy:void 0;return{site:a,entries:s,i18n:{defaultLocale:d,routingStrategy:t.includes(f??``)?f:i.routingStrategy},install:i}}async function T(){let e=o();if(e.entities.has(`locale`))return(await y(e)).defaultLocale}export{w as a,y as i,f as n,C as o,_ as r,v as t};
|
|
2
|
+
//# sourceMappingURL=locale-registry-COsJrVZl.mjs.map
|