@murumets-ee/entity 0.10.0 → 0.12.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/count-cache.ts","../../src/cursor.ts","../../src/admin-config.ts","../../src/fields/base.ts","../../src/behaviors/types.ts","../../src/define-entity.ts","../../src/shared/entity-data-ops.ts","../../src/types/infer.ts","../../src/types/logger.ts","../../src/query/client.ts"],"mappings":";;;;;;;;AAiBA;;;;;;;;;;;UAAiB,cAAA;EACf,GAAA,CAAI,GAAA;EACJ,GAAA,CAAI,GAAA,UAAa,KAAA;EAYjB;;;;;;;ACNF;;;EDKE,YAAA,CAAa,GAAA,UAAa,OAAA,QAAe,OAAA,WAAkB,OAAA;EAC3D,UAAA,CAAW,MAAA;AAAA;;;;UCNI,WAAA;EDMJ;ECJX,KAAA;EDIyB;ECFzB,KAAA;;EAEA,SAAA;EANe;EAQf,EAAA;AAAA;;;;;;;UC7Be,iBAAA;EFaA;EEXf,KAAA;;EAEA,KAAA;EFUA;EERA,aAAA;EFSA;EEPA,IAAA;EFOiB;EELjB,WAAA;EFgBa;EEdb,MAAA;EFc0B;EEZ1B,YAAA;EFaA;EEXA,aAAA;EFWyB;EETzB,cAAA,GAAiB,MAAA;IAAiB,KAAA;IAAgB,WAAA;IAAsB,WAAA;EAAA;EDG9C;ECD1B,WAAA;EDC0B;ECC1B,oBAAA;EDGA;ECDA,QAAA;EDKA;ECHA,UAAA;EDGE;ECDF,aAAA;;EAEA,SAAA;EA9Be;;;;;EAoCf,MAAA;EA9BA;;;;;EAoCA,YAAA;EAxBA;;;;EA6BA,iBAAA;AAAA;;;;;;;UC9Ce,eAAA;EACf,QAAA;EACA,OAAA;EACA,YAAA;EACA,OAAA;EACA,MAAA;EACA,MAAA;IACE,IAAA;IACA,IAAA;EAAA;AAAA;AAAA,UAIa,OAAA,SAAgB,eAAA;EAC/B,IAAA;AA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AAe,MAAA,SAAe,WAAA;EAAA,QAEvD,MAAA;EAAA,QACA,EAAA;EAAA,QACA,MAAA;EAAA,QAEA,KAAA;EAAA,QACA,aAAA;EAAA,QACA,UAAA;EAAA,QACA,eAAA;EN7FsB;EAAA,YMgGlB,GAAA,CAAA;cASA,MAAA,EAAQ,iBAAA,CAAkB,SAAA;ENtGtC;;;;;EMgIM,QAAA,CAAS,EAAA,UAAY,OAAA,GAAU,eAAA,GAAkB,OAAA,CAAQ,cAAA,CAAe,SAAA;EN3HxE;;AAIR;;;EM+KQ,QAAA,CAAS,OAAA,GAAU,eAAA,GAAkB,OAAA,CAAQ,cAAA,CAAe,SAAA;EN9K9D;AAGN;;;EMqQQ,KAAA,CAAM,OAAA,GAAU,YAAA,GAAe,OAAA;ENrQJ;;;;;EAAA,QMsSzB,kBAAA;AAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/count-cache.ts","../../src/cursor.ts","../../src/admin-config.ts","../../src/fields/base.ts","../../src/behaviors/types.ts","../../src/define-entity.ts","../../src/shared/entity-data-ops.ts","../../src/types/infer.ts","../../src/types/logger.ts","../../src/query/client.ts"],"mappings":";;;;;;;;AAiBA;;;;;;;;;;;UAAiB,cAAA;EACf,GAAA,CAAI,GAAA;EACJ,GAAA,CAAI,GAAA,UAAa,KAAA;EAYjB;;;;;;;ACNF;;;EDKE,YAAA,CAAa,GAAA,UAAa,OAAA,QAAe,OAAA,WAAkB,OAAA;EAC3D,UAAA,CAAW,MAAA;AAAA;;;;UCNI,WAAA;EDMJ;ECJX,KAAA;EDIyB;ECFzB,KAAA;;EAEA,SAAA;EANe;EAQf,EAAA;AAAA;;;;;;;UC7Be,iBAAA;EFaA;EEXf,KAAA;;EAEA,KAAA;EFUA;EERA,aAAA;EFSA;EEPA,IAAA;EFOiB;EELjB,WAAA;EFgBa;EEdb,MAAA;EFc0B;EEZ1B,YAAA;EFaA;EEXA,aAAA;EFWyB;EETzB,cAAA,GAAiB,MAAA;IAAiB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+1,4 @@
1
- import{schemaRegistry as e}from"@murumets-ee/db";import{and as t,eq as n,getTableColumns as r,gt as i,inArray as a,isNull as o,lt as s,or as c,sql as l}from"drizzle-orm";function u(e,a){let o=r(e),l=o[a.field];if(!l)return null;let u=a.direction===`desc`?s:i,d=u(l,a.value);if(!a.id)return d;let f=o.id;if(!f)return d;let p=u(f,a.id);return c(d,t(n(l,a.value),p))??d}function d(e,t,n){if(!t)return null;let r={},i=n?.select||Object.keys(e.allFields);for(let a of i){if(!n?.includeInternal&&a.startsWith(`_`))continue;let i=e.allFields[a];i&&i.type!==`blocks`&&(r[a]=t[a])}return r}function f(e,t,n){return t.map(t=>d(e,t,n))}function p(e){return e.entity.allFields}function m(e){return Object.entries(p(e)).filter(([e,t])=>t.type===`blocks`).map(([e,t])=>({name:e,config:t}))}async function h(r,i,o){if(!i.length)return i;let s=`${r.entity.name}_translations`,c=e.get(s);if(!c)return i;let l=i.map(e=>e.id),u=await r.db.select().from(c).where(t(a(c.entityId,l),n(c.locale,o))),d=Object.entries(p(r)).filter(([e,t])=>t.translatable).map(([e])=>e),f=new Map;for(let e of u){let t={};for(let n of d){let r=e[n];r!=null&&(t[n]=r)}f.set(e.entityId,t)}return i.map(e=>{let t=f.get(e.id);return t?{...e,...t}:e})}async function g(r,i,s,l){let u=m(r);if(u.length===0||i.length===0)return new Map;let d=e.get(`${r.entity.name}_layout`);if(!d)return new Map;let f=u.filter(({config:e})=>!(`localized`in e&&e.localized)),p=u.filter(({config:e})=>`localized`in e&&e.localized),h=new Map;if(f.length>0){let c=await r.db.select().from(d).where(t(a(d.entityId,i),o(d.locale))).orderBy(d.sortOrder),u;if(s&&c.length>0){let i=e.get(`${r.entity.name}_layout_translations`);if(i){let e=c.map(e=>e.id),o=await r.db.select().from(i).where(t(a(i.layoutId,e),n(i.locale,s)));u=new Map;for(let e of o)u.set(e.layoutId,e.fields??{})}}let p;if(l?.strictTranslations){p=new Map;for(let{config:e}of f)if(e.type===`blocks`)for(let t of e.blocks)p.set(t.slug,t.fields)}for(let e of c){let t=e.entityId,n=e.fieldName,r=h.get(t);r||(r={},h.set(t,r)),r[n]||(r[n]=[]);let i=e.data??{},a=u?.get(e.id),o={_block:e.blockType,_id:e.id,...i,...a??{}};if(s&&p){let t=e.blockType,n=p.get(t);if(n)for(let[e,t]of Object.entries(n))t.translatable&&!a?.[e]&&(o[e]=``)}r[n].push(o)}}if(p.length>0){let e=!s||s===l?.defaultLocale,u;u=s?e?c(n(d.locale,s),o(d.locale))??n(d.locale,s):n(d.locale,s):o(d.locale);let f=await r.db.select().from(d).where(t(a(d.entityId,i),u)).orderBy(d.sortOrder),p=new Map;for(let e of f){let t=`${e.entityId}::${e.fieldName}`,n=p.get(t);n||(n={localeRows:[],nullRows:[]},p.set(t,n)),e.locale?n.localeRows.push(e):n.nullRows.push(e)}for(let[,{localeRows:e,nullRows:t}]of p){let n=e.length>0?e:t;for(let e of n){let t=e.entityId,n=e.fieldName,r=h.get(t);r||(r={},h.set(t,r)),r[n]||(r[n]=[]);let i=e.data??{};r[n].push({_block:e.blockType,_id:e.id,...i})}}}return h}function _(e,t,n){let r=m(e);if(r.length!==0)for(let e of t){let t=e.id,i=n.get(t)??{};for(let{name:t}of r)e[t]=i[t]??[]}}function v(e,t,n,r){let i=n?`${n}:${e}`:e;return r&&(i=`${i}@${r}`),t?`${i}:${String(t)}`:i}var y=class extends Error{constructor(e){super(e),this.name=`ForbiddenError`}};async function b(e){if(!e)throw new y(`No context resolver configured on AdminClient/QueryClient. Use createAdminClient() from @murumets-ee/core/clients, or pass a contextResolver in config.`);let t=await e();if(!t)throw new y(`Context resolver returned no context. Ensure auth is configured in your request handler, or use runAsCli() for CLI scripts.`);return t}function x(e,t){return n(e.table._scopeId,t)}async function S(e,t,n,r){let i=await b(t),a=i.user.groups[0];if(!a)throw new y(`User '${i.user.id}' has no role assigned.`);if(!i.checker(a,e.name,n))throw new y(`Forbidden: role '${a}' cannot ${n} '${e.name}'`);let o;if(e.scope&&e.scope!==`global`&&(o=i.scope?.id,!o&&r?.strictScope))throw new y(`Entity '${e.name}' requires scope '${e.scope}' but no scope is set in context.`);let s={user:{id:i.user.id,name:i.user.name,email:i.user.email}};return{security:i,scopeId:o,behaviorCtx:s}}var C=class{entity;db;logger;table;isPublishable;countCache;contextResolver;get ctx(){return{entity:this.entity,db:this.db,table:this.table,resolveContext:this.contextResolver}}constructor(t){this.entity=t.entity,this.db=t.db,this.logger=t.logger,this.countCache=t.countCache,this.contextResolver=t.contextResolver,this.isPublishable=t.entity.behaviors?.some(e=>e.name===`publishable`)??!1;let n=e.get(t.entity.name);if(!n)throw Error(`Schema for entity '${t.entity.name}' not found in registry. Ensure schemas are generated and registered before creating QueryClient.`);this.table=n}async findById(e,r){this.logger?.info({entity:this.entity.name,id:e,locale:r?.locale},`Query: Finding entity by ID`);let{scopeId:i}=await S(this.entity,this.contextResolver,`view`),a=[n(this.table.id,e)];i&&a.push(x(this.ctx,i)),this.isPublishable&&a.push(this.buildPublishFilter(r?.locale));let[o]=await this.db.select().from(this.table).where(t(...a));if(!o)return null;let s=d(this.entity,o,{select:r?.select});if(!s)return null;if(m(this.ctx).length>0){let e=await g(this.ctx,[s.id],r?.locale,{defaultLocale:r?.defaultLocale});_(this.ctx,[s],e)}return r?.locale?(await h(this.ctx,[s],r.locale))[0]:s}async findMany(e){this.logger?.info({entity:this.entity.name,options:e,locale:e?.locale},`Query: Finding entities`);let{scopeId:n}=await S(this.entity,this.contextResolver,`view`),r=this.db.select().from(this.table).$dynamic(),i=[];if(n&&i.push(x(this.ctx,n)),this.isPublishable&&i.push(this.buildPublishFilter(e?.locale)),e?.where&&i.push(e.where),e?.cursor){let t=p(this.ctx);if(!(e.cursor.field in t)&&e.cursor.field!==`id`)throw Error(`Invalid cursor field: '${e.cursor.field}' is not a field on '${this.entity.name}'`);let n=u(this.table,e.cursor);n&&i.push(n)}if(i.length>0&&(r=r.where(t(...i))),e?.limit&&(r=r.limit(e.limit)),e?.offset&&!e?.cursor&&(r=r.offset(e.offset)),e?.orderBy){let t=Array.isArray(e.orderBy)?e.orderBy:[e.orderBy];r=r.orderBy(...t)}let a=await r,o=f(this.entity,a,{select:e?.select}).filter(e=>e!==null);if(m(this.ctx).length>0&&o.length>0){let t=o.map(e=>e.id),n=await g(this.ctx,t,e?.locale,{defaultLocale:e?.defaultLocale});_(this.ctx,o,n)}return e?.locale?await h(this.ctx,o,e.locale):o}async count(e){this.logger?.info({entity:this.entity.name,options:e},`Query: Counting entities`);let{scopeId:n}=await S(this.entity,this.contextResolver,`view`),r=v(this.entity.name,e?.where,`query`,n),i=async()=>{let r=this.db.select({count:l`count(*)`}).from(this.table).$dynamic(),i=[];n&&i.push(x(this.ctx,n)),this.isPublishable&&i.push(this.buildPublishFilter()),e?.where&&i.push(e.where),i.length>0&&(r=r.where(t(...i)));let[a]=await r;return Number(a.count)};return this.countCache?this.countCache.getOrCompute(r,i):i()}buildPublishFilter(t){if(t){let n=e.get(`${this.entity.name}_locale_status`);if(n)return l`COALESCE(
1
+ import{schemaRegistry as e}from"@murumets-ee/db";import{and as t,eq as n,getTableColumns as r,gt as i,inArray as a,isNull as o,lt as s,or as c,sql as l}from"drizzle-orm";function u(e,a){let o=r(e),l=o[a.field];if(!l)return null;let u=a.direction===`desc`?s:i,d=u(l,a.value);if(!a.id)return d;let f=o.id;if(!f)return d;let p=u(f,a.id);return c(d,t(n(l,a.value),p))??d}function d(e,t,n){if(!t)return null;let r={},i=n?.select||Object.keys(e.allFields);for(let a of i){let i=e.allFields[a];if(!n?.includeInternal){let e=a.startsWith(`_`),t=i?.internal===!0;if(e||t)continue}i&&i.type!==`blocks`&&(r[a]=t[a])}return r}function f(e,t,n){return t.map(t=>d(e,t,n))}function p(e){return e.entity.allFields}function m(e){return Object.entries(p(e)).filter(([e,t])=>t.type===`blocks`).map(([e,t])=>({name:e,config:t}))}async function h(r,i,o){if(!i.length)return i;let s=`${r.entity.name}_translations`,c=e.get(s);if(!c)return i;let l=i.map(e=>e.id),u=await r.db.select().from(c).where(t(a(c.entityId,l),n(c.locale,o))),d=Object.entries(p(r)).filter(([e,t])=>t.translatable).map(([e])=>e),f=new Map;for(let e of u){let t={};for(let n of d){let r=e[n];r!=null&&(t[n]=r)}f.set(e.entityId,t)}return i.map(e=>{let t=f.get(e.id);return t?{...e,...t}:e})}async function g(r,i,s,l){let u=m(r);if(u.length===0||i.length===0)return new Map;let d=e.get(`${r.entity.name}_layout`);if(!d)return new Map;let f=u.filter(({config:e})=>!(`localized`in e&&e.localized)),p=u.filter(({config:e})=>`localized`in e&&e.localized),h=new Map;if(f.length>0){let c=await r.db.select().from(d).where(t(a(d.entityId,i),o(d.locale))).orderBy(d.sortOrder),u;if(s&&c.length>0){let i=e.get(`${r.entity.name}_layout_translations`);if(i){let e=c.map(e=>e.id),o=await r.db.select().from(i).where(t(a(i.layoutId,e),n(i.locale,s)));u=new Map;for(let e of o)u.set(e.layoutId,e.fields??{})}}let p;if(l?.strictTranslations){p=new Map;for(let{config:e}of f)if(e.type===`blocks`)for(let t of e.blocks)p.set(t.slug,t.fields)}for(let e of c){let t=e.entityId,n=e.fieldName,r=h.get(t);r||(r={},h.set(t,r)),r[n]||(r[n]=[]);let i=e.data??{},a=u?.get(e.id),o={_block:e.blockType,_id:e.id,...i,...a??{}};if(s&&p){let t=e.blockType,n=p.get(t);if(n)for(let[e,t]of Object.entries(n))t.translatable&&!a?.[e]&&(o[e]=``)}r[n].push(o)}}if(p.length>0){let e=!s||s===l?.defaultLocale,u;u=s?e?c(n(d.locale,s),o(d.locale))??n(d.locale,s):n(d.locale,s):o(d.locale);let f=await r.db.select().from(d).where(t(a(d.entityId,i),u)).orderBy(d.sortOrder),p=new Map;for(let e of f){let t=`${e.entityId}::${e.fieldName}`,n=p.get(t);n||(n={localeRows:[],nullRows:[]},p.set(t,n)),e.locale?n.localeRows.push(e):n.nullRows.push(e)}for(let[,{localeRows:e,nullRows:t}]of p){let n=e.length>0?e:t;for(let e of n){let t=e.entityId,n=e.fieldName,r=h.get(t);r||(r={},h.set(t,r)),r[n]||(r[n]=[]);let i=e.data??{};r[n].push({_block:e.blockType,_id:e.id,...i})}}}return h}function _(e,t,n){let r=m(e);if(r.length!==0)for(let e of t){let t=e.id,i=n.get(t)??{};for(let{name:t}of r)e[t]=i[t]??[]}}function v(e,t,n,r){let i=n?`${n}:${e}`:e;return r&&(i=`${i}@${r}`),t?`${i}:${String(t)}`:i}var y=class extends Error{constructor(e){super(e),this.name=`ForbiddenError`}};async function b(e){if(!e)throw new y(`No context resolver configured on AdminClient/QueryClient. Use createAdminClient() from @murumets-ee/core/clients, or pass a contextResolver in config.`);let t=await e();if(!t)throw new y(`Context resolver returned no context. Ensure auth is configured in your request handler, or use runAsCli() for CLI scripts.`);return t}function x(e,t){return n(e.table._scopeId,t)}async function S(e,t,n,r){let i=await b(t),a=i.user.groups[0];if(!a)throw new y(`User '${i.user.id}' has no role assigned.`);if(!i.checker(a,e.name,n))throw new y(`Forbidden: role '${a}' cannot ${n} '${e.name}'`);let o;if(e.scope&&e.scope!==`global`&&(o=i.scope?.id,!o&&r?.strictScope))throw new y(`Entity '${e.name}' requires scope '${e.scope}' but no scope is set in context.`);let s={user:{id:i.user.id,...i.user.name!==void 0&&{name:i.user.name},...i.user.email!==void 0&&{email:i.user.email}},...r?.enqueueOnCommit!==void 0&&{enqueueOnCommit:r.enqueueOnCommit}};return{security:i,scopeId:o,behaviorCtx:s}}var C=class{entity;db;logger;table;isPublishable;countCache;contextResolver;get ctx(){return{entity:this.entity,db:this.db,table:this.table,resolveContext:this.contextResolver}}constructor(t){this.entity=t.entity,this.db=t.db,this.logger=t.logger,this.countCache=t.countCache,this.contextResolver=t.contextResolver,this.isPublishable=t.entity.behaviors?.some(e=>e.name===`publishable`)??!1;let n=e.get(t.entity.name);if(!n)throw Error(`Schema for entity '${t.entity.name}' not found in registry. Ensure schemas are generated and registered before creating QueryClient.`);this.table=n}async findById(e,r){this.logger?.info({entity:this.entity.name,id:e,locale:r?.locale},`Query: Finding entity by ID`);let{scopeId:i}=await S(this.entity,this.contextResolver,`view`),a=[n(this.table.id,e)];i&&a.push(x(this.ctx,i)),this.isPublishable&&a.push(this.buildPublishFilter(r?.locale));let[o]=await this.db.select().from(this.table).where(t(...a));if(!o)return null;let s=d(this.entity,o,{select:r?.select});if(!s)return null;if(m(this.ctx).length>0){let e=await g(this.ctx,[s.id],r?.locale,{defaultLocale:r?.defaultLocale});_(this.ctx,[s],e)}return r?.locale?(await h(this.ctx,[s],r.locale))[0]:s}async findMany(e){this.logger?.info({entity:this.entity.name,options:e,locale:e?.locale},`Query: Finding entities`);let{scopeId:n}=await S(this.entity,this.contextResolver,`view`),r=this.db.select().from(this.table).$dynamic(),i=[];if(n&&i.push(x(this.ctx,n)),this.isPublishable&&i.push(this.buildPublishFilter(e?.locale)),e?.where&&i.push(e.where),e?.cursor){let t=p(this.ctx);if(!Object.hasOwn(t,e.cursor.field)&&e.cursor.field!==`id`)throw Error(`Invalid cursor field: '${e.cursor.field}' is not a field on '${this.entity.name}'`);let n=u(this.table,e.cursor);n&&i.push(n)}if(i.length>0&&(r=r.where(t(...i))),e?.limit&&(r=r.limit(e.limit)),e?.offset&&!e?.cursor&&(r=r.offset(e.offset)),e?.orderBy){let t=Array.isArray(e.orderBy)?e.orderBy:[e.orderBy];r=r.orderBy(...t)}let a=await r,o=f(this.entity,a,{select:e?.select}).filter(e=>e!==null);if(m(this.ctx).length>0&&o.length>0){let t=o.map(e=>e.id),n=await g(this.ctx,t,e?.locale,{defaultLocale:e?.defaultLocale});_(this.ctx,o,n)}return e?.locale?await h(this.ctx,o,e.locale):o}async count(e){this.logger?.info({entity:this.entity.name,options:e},`Query: Counting entities`);let{scopeId:n}=await S(this.entity,this.contextResolver,`view`),r=v(this.entity.name,e?.where,`query`,n),i=async()=>{let r=this.db.select({count:l`count(*)`}).from(this.table).$dynamic(),i=[];n&&i.push(x(this.ctx,n)),this.isPublishable&&i.push(this.buildPublishFilter()),e?.where&&i.push(e.where),i.length>0&&(r=r.where(t(...i)));let[a]=await r;if(!a)throw Error(`count query returned no row for ${this.entity.name}`);return Number(a.count)};return this.countCache?this.countCache.getOrCompute(r,i):i()}buildPublishFilter(t){if(t){let n=e.get(`${this.entity.name}_locale_status`);if(n)return l`COALESCE(
2
2
  (SELECT ${n.status} FROM ${n}
3
3
  WHERE ${n.entityId} = ${this.table.id}
4
4
  AND ${n.locale} = ${t}),
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/cursor.ts","../../src/dto-shaper.ts","../../src/shared/entity-data-ops.ts","../../src/query/client.ts"],"sourcesContent":["/**\n * Cursor-based (keyset) pagination utilities.\n *\n * Cursor pagination avoids the performance cliff of OFFSET at scale (1M+ rows).\n * Instead of `OFFSET N`, it uses a WHERE condition:\n * `WHERE (sortField < lastValue) OR (sortField = lastValue AND id < lastId)`\n * which Postgres can serve from an index in constant time.\n *\n * The cursor is opaque to the client — base64-encoded JSON.\n *\n * Security:\n * - `field` must be whitelisted against the entity's actual fields\n * - `id` must be a valid UUID\n * - `value` is parameterized (never interpolated into SQL)\n * - Malformed cursors return null (caller returns 400)\n */\n\nimport { and, eq, getTableColumns, gt, lt, or, type SQL } from 'drizzle-orm'\nimport type { PgTable } from 'drizzle-orm/pg-core'\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Cursor input for keyset pagination. */\nexport interface CursorInput {\n /** Sort field name (e.g. 'createdAt'). Must be a real column on the entity. */\n field: string\n /** Last seen value of the sort field. */\n value: string | number\n /** Sort direction — must match the ORDER BY direction. */\n direction: 'asc' | 'desc'\n /** Tie-breaker: last seen entity ID. Required for non-unique sort fields. */\n id?: string\n}\n\n/** Decoded cursor (internal, after validation). */\ninterface DecodedCursor {\n field: string\n value: string | number\n direction: 'asc' | 'desc'\n id?: string\n}\n\n// ---------------------------------------------------------------------------\n// UUID validation (same format used throughout the toolkit)\n// ---------------------------------------------------------------------------\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n// ---------------------------------------------------------------------------\n// Encode / decode\n// ---------------------------------------------------------------------------\n\n/**\n * Encode a cursor for API transport (base64url).\n * Built from the last item in a result set.\n */\nexport function encodeCursor(\n item: Record<string, unknown>,\n sortField: string,\n direction: 'asc' | 'desc',\n): string {\n const payload: CursorInput = {\n field: sortField,\n value: item[sortField] as string | number,\n direction,\n id: item.id as string | undefined,\n }\n return btoa(JSON.stringify(payload))\n}\n\n/**\n * Decode and validate a cursor string from query params.\n * Returns null if the cursor is malformed, tampered, or invalid.\n *\n * Security: the `field` value is NOT validated here — the caller must\n * whitelist it against the entity's actual columns.\n */\nexport function decodeCursor(encoded: string): DecodedCursor | null {\n try {\n const json = atob(encoded)\n const parsed: unknown = JSON.parse(json)\n\n if (typeof parsed !== 'object' || parsed === null) return null\n const obj = parsed as Record<string, unknown>\n\n // Validate field\n if (typeof obj.field !== 'string' || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(obj.field)) {\n return null\n }\n\n // Validate value (string or number)\n if (typeof obj.value !== 'string' && typeof obj.value !== 'number') {\n return null\n }\n\n // Validate direction\n if (obj.direction !== 'asc' && obj.direction !== 'desc') {\n return null\n }\n\n // Validate id (optional, must be UUID if present)\n if (obj.id !== undefined) {\n if (typeof obj.id !== 'string' || !UUID_RE.test(obj.id)) {\n return null\n }\n }\n\n return {\n field: obj.field,\n value: obj.value,\n direction: obj.direction,\n id: obj.id as string | undefined,\n }\n } catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// SQL condition builder\n// ---------------------------------------------------------------------------\n\n/**\n * Build the keyset WHERE condition from a decoded cursor.\n *\n * For DESC: `WHERE (field < value) OR (field = value AND id < cursorId)`\n * For ASC: `WHERE (field > value) OR (field = value AND id > cursorId)`\n *\n * The caller must verify that `cursor.field` exists on the table before calling.\n *\n * @param table - Drizzle table with columns\n * @param cursor - Decoded and validated cursor\n * @returns SQL condition, or null if the field doesn't exist on the table\n */\nexport function buildCursorCondition(table: PgTable, cursor: DecodedCursor): SQL | null {\n const cols = getTableColumns(table)\n const column = cols[cursor.field]\n if (!column) return null\n\n const isDesc = cursor.direction === 'desc'\n const compare = isDesc ? lt : gt\n\n // Primary condition: sort field passes the cursor value\n const fieldCondition = compare(column, cursor.value)\n\n // Without tie-breaker ID, use simple comparison\n if (!cursor.id) {\n return fieldCondition\n }\n\n // With tie-breaker: (field < value) OR (field = value AND id < cursorId)\n const idColumn = cols.id\n if (!idColumn) return fieldCondition\n\n const idCondition = compare(idColumn, cursor.id)\n // Drizzle's `or`/`and` return SQL when called with at least one defined arg.\n // Fall back to fieldCondition rather than asserting non-null.\n return or(fieldCondition, and(eq(column, cursor.value), idCondition)) ?? fieldCondition\n}\n","/**\n * DTO Shaper\n * Transforms raw DB rows into clean DTOs.\n * All fields are real columns — just read from row directly.\n */\n\nimport type { Entity } from './define-entity.js'\nimport type { FieldConfig } from './fields/base.js'\nimport type { InferEntityDTO } from './types/infer.js'\n\nexport interface ShapeDtoOptions {\n select?: string[] // Explicit field selection\n includeInternal?: boolean // Include _version, _scopeId\n}\n\n/**\n * Shape a raw DB row into a typed DTO.\n * Every field is a real column — read directly from row.\n */\nexport function shapeDto<AllFields extends Record<string, FieldConfig>>(\n entity: Entity<AllFields>,\n row: Record<string, unknown>,\n options?: ShapeDtoOptions,\n): InferEntityDTO<AllFields> | null {\n if (!row) return null\n\n const result: Record<string, unknown> = {}\n const fieldsToInclude = options?.select || Object.keys(entity.allFields)\n\n for (const fieldName of fieldsToInclude) {\n if (!options?.includeInternal && fieldName.startsWith('_')) continue\n\n const fieldConfig = (entity.allFields as Record<string, FieldConfig>)[fieldName]\n if (!fieldConfig) continue\n\n // Blocks are loaded separately from layout tables\n if (fieldConfig.type === 'blocks') continue\n\n result[fieldName] = row[fieldName]\n }\n\n return result as InferEntityDTO<AllFields>\n}\n\n/**\n * Shape multiple rows\n */\nexport function shapeDtos<AllFields extends Record<string, FieldConfig>>(\n entity: Entity<AllFields>,\n rows: Record<string, unknown>[],\n options?: ShapeDtoOptions,\n): (InferEntityDTO<AllFields> | null)[] {\n return rows.map((row) => shapeDto(entity, row, options))\n}\n","/**\n * Shared entity data operations.\n *\n * Extracted from AdminClient and QueryClient to eliminate duplication.\n * These are standalone functions that take an EntityContext — both clients\n * satisfy this interface via `this`.\n */\n\nimport { schemaRegistry } from '@murumets-ee/db'\nimport { and, eq, inArray, isNull, or, type SQL } from 'drizzle-orm'\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { Entity } from '../define-entity.js'\nimport type { FieldConfig } from '../fields/base.js'\n\n// ---------------------------------------------------------------------------\n// Context interface — satisfied by both AdminClient and QueryClient via `this`\n// ---------------------------------------------------------------------------\n\n/**\n * Security context resolved per-request. Provided by the consumer\n * (e.g., via React.cache() in Next.js, or runAsCli for CLI).\n * The entity package has zero knowledge of how this is resolved.\n */\nexport interface SecurityContext {\n user: { id: string; groups: string[]; name?: string; email?: string }\n checker: (role: string, resource: string, action: string) => boolean\n scope?: { type: string; id: string }\n}\n\n/**\n * Function that resolves the current request's security context.\n * Injected at construction time — the entity package never imports\n * @murumets-ee/core or any framework-specific code.\n *\n * Returns undefined only when intentionally skipping enforcement\n * (should not happen in production — throw ForbiddenError instead).\n */\nexport type ContextResolver = () =>\n | SecurityContext\n | undefined\n | Promise<SecurityContext | undefined>\n\nexport interface EntityContext {\n entity: Entity\n db: PostgresJsDatabase\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any>\n table: PgTableWithColumns<any>\n /** Resolves the current request's security context. */\n resolveContext?: ContextResolver\n}\n\n// ---------------------------------------------------------------------------\n// Field accessors\n// ---------------------------------------------------------------------------\n\n/** Get the entity's full field map with proper typing. Eliminates repeated casts. */\nexport function getAllFields(ctx: EntityContext): Record<string, FieldConfig> {\n return ctx.entity.allFields as Record<string, FieldConfig>\n}\n\n/** Get all blocks field definitions for this entity. */\nexport function getBlocksFields(ctx: EntityContext): Array<{ name: string; config: FieldConfig }> {\n return Object.entries(getAllFields(ctx))\n .filter(([_, config]) => config.type === 'blocks')\n .map(([name, config]) => ({ name, config }))\n}\n\n// ---------------------------------------------------------------------------\n// Translation merging\n// ---------------------------------------------------------------------------\n\n/**\n * Merge translations into entities for the specified locale.\n * Reads translatable field values from real columns on the translation row.\n */\nexport async function mergeTranslations<T extends Record<string, unknown>>(\n ctx: EntityContext,\n entities: T[],\n locale: string,\n): Promise<T[]> {\n if (!entities.length) return entities\n\n const translationTableName = `${ctx.entity.name}_translations`\n const translationTable = schemaRegistry.get(translationTableName)\n\n if (!translationTable) return entities\n\n const entityIds = entities.map((e) => e.id)\n\n const translations = await ctx.db\n .select()\n .from(translationTable)\n .where(and(inArray(translationTable.entityId, entityIds), eq(translationTable.locale, locale)))\n\n // Get translatable field names\n const translatableFields = Object.entries(getAllFields(ctx))\n .filter(([_, config]) => config.translatable)\n .map(([name]) => name)\n\n const translationMap = new Map<unknown, Record<string, unknown>>()\n for (const translation of translations) {\n const translatedValues: Record<string, unknown> = {}\n for (const fieldName of translatableFields) {\n const value = (translation as Record<string, unknown>)[fieldName]\n if (value !== undefined && value !== null) {\n translatedValues[fieldName] = value\n }\n }\n translationMap.set(translation.entityId, translatedValues)\n }\n\n return entities.map((entity) => {\n const translatedFields = translationMap.get(entity.id)\n if (!translatedFields) return entity\n return { ...entity, ...translatedFields }\n })\n}\n\n// ---------------------------------------------------------------------------\n// Block loading\n// ---------------------------------------------------------------------------\n\nexport interface LoadBlocksOptions {\n defaultLocale?: string\n /**\n * When true (admin editing), clears untranslated translatable block fields\n * to empty string — signals incomplete translation in the editing UI.\n * When false (visitor-facing), preserves base data as fallback.\n */\n strictTranslations?: boolean\n}\n\n/**\n * Load blocks for one or more entities from the layout table.\n *\n * Handles both block translation modes:\n * - Shared layout (localized: false): loads locale=NULL rows, merges translations\n * - Per-locale layout (localized: true): loads rows matching the provided locale only\n */\nexport async function loadBlocks(\n ctx: EntityContext,\n entityIds: string[],\n locale?: string,\n options?: LoadBlocksOptions,\n): Promise<Map<string, Record<string, unknown[]>>> {\n const blocksFields = getBlocksFields(ctx)\n if (blocksFields.length === 0 || entityIds.length === 0) {\n return new Map()\n }\n\n const layoutTable = schemaRegistry.get(`${ctx.entity.name}_layout`)\n if (!layoutTable) return new Map()\n\n // Determine block field modes\n const sharedFields = blocksFields.filter(\n ({ config }) => !('localized' in config && config.localized),\n )\n const localizedFields = blocksFields.filter(\n ({ config }) => 'localized' in config && config.localized,\n )\n\n const result = new Map<string, Record<string, unknown[]>>()\n\n // ---- Shared blocks: locale IS NULL, translations from layout_translations ----\n if (sharedFields.length > 0) {\n const rows = await ctx.db\n .select()\n .from(layoutTable)\n .where(and(inArray(layoutTable.entityId, entityIds), isNull(layoutTable.locale)))\n .orderBy(layoutTable.sortOrder)\n\n // Load translations if locale provided\n let blockTransMap: Map<string, Record<string, unknown>> | undefined\n if (locale && rows.length > 0) {\n const layoutTransTable = schemaRegistry.get(`${ctx.entity.name}_layout_translations`)\n if (layoutTransTable) {\n const layoutIds = rows.map((r) => r.id as string)\n const translations = await ctx.db\n .select()\n .from(layoutTransTable)\n .where(\n and(inArray(layoutTransTable.layoutId, layoutIds), eq(layoutTransTable.locale, locale)),\n )\n\n blockTransMap = new Map()\n for (const t of translations) {\n blockTransMap.set(t.layoutId as string, (t.fields as Record<string, unknown>) ?? {})\n }\n }\n }\n\n // Build block definition lookup for translatable field clearing (strict mode only)\n let blockDefMap: Map<string, Record<string, FieldConfig>> | undefined\n if (options?.strictTranslations) {\n blockDefMap = new Map()\n for (const { config } of sharedFields) {\n if (config.type !== 'blocks') continue\n for (const def of config.blocks) {\n blockDefMap.set(def.slug, def.fields)\n }\n }\n }\n\n for (const row of rows) {\n const eid = row.entityId as string\n const fname = row.fieldName as string\n\n let entityBlocks = result.get(eid)\n if (!entityBlocks) {\n entityBlocks = {}\n result.set(eid, entityBlocks)\n }\n if (!entityBlocks[fname]) entityBlocks[fname] = []\n\n const blockData = (row.data as Record<string, unknown>) ?? {}\n const translatedFields = blockTransMap?.get(row.id as string)\n\n // Build the block object\n const block: Record<string, unknown> = {\n _block: row.blockType,\n _id: row.id,\n ...blockData,\n ...(translatedFields ?? {}),\n }\n\n // Strict mode: clear untranslated translatable fields when loading for non-default locale\n if (locale && blockDefMap) {\n const blockType = row.blockType as string\n const fieldDefs = blockDefMap.get(blockType)\n if (fieldDefs) {\n for (const [fieldName, fieldConfig] of Object.entries(fieldDefs)) {\n if (fieldConfig.translatable && !translatedFields?.[fieldName]) {\n block[fieldName] = ''\n }\n }\n }\n }\n\n entityBlocks[fname].push(block)\n }\n }\n\n // ---- Localized blocks: filter by locale column ----\n // NULL rows (from initial create) only fall back for the default locale.\n // Non-default locales without locale-specific rows get an empty array.\n if (localizedFields.length > 0) {\n const isDefault = !locale || locale === options?.defaultLocale\n let localeCondition: SQL\n if (locale) {\n if (isDefault) {\n // Both args defined → drizzle's `or` always returns SQL; fall back defensively\n localeCondition =\n or(eq(layoutTable.locale, locale), isNull(layoutTable.locale)) ??\n eq(layoutTable.locale, locale)\n } else {\n localeCondition = eq(layoutTable.locale, locale)\n }\n } else {\n localeCondition = isNull(layoutTable.locale)\n }\n\n const rows = await ctx.db\n .select()\n .from(layoutTable)\n .where(and(inArray(layoutTable.entityId, entityIds), localeCondition))\n .orderBy(layoutTable.sortOrder)\n\n // Group by entityId + fieldName, prefer locale-specific rows over NULL\n const grouped = new Map<string, { localeRows: typeof rows; nullRows: typeof rows }>()\n for (const row of rows) {\n const key = `${row.entityId}::${row.fieldName}`\n let group = grouped.get(key)\n if (!group) {\n group = { localeRows: [], nullRows: [] }\n grouped.set(key, group)\n }\n if (row.locale) {\n group.localeRows.push(row)\n } else {\n group.nullRows.push(row)\n }\n }\n\n for (const [, { localeRows, nullRows }] of grouped) {\n // Use locale-specific rows if available, otherwise fall back to NULL\n const effective = localeRows.length > 0 ? localeRows : nullRows\n\n for (const row of effective) {\n const eid = row.entityId as string\n const fname = row.fieldName as string\n\n let entityBlocks = result.get(eid)\n if (!entityBlocks) {\n entityBlocks = {}\n result.set(eid, entityBlocks)\n }\n if (!entityBlocks[fname]) entityBlocks[fname] = []\n\n const blockData = (row.data as Record<string, unknown>) ?? {}\n\n entityBlocks[fname].push({\n _block: row.blockType,\n _id: row.id,\n ...blockData,\n })\n }\n }\n }\n\n return result\n}\n\n/**\n * Attach loaded blocks to shaped DTOs.\n */\nexport function attachBlocks(\n ctx: EntityContext,\n entities: Record<string, unknown>[],\n blocksMap: Map<string, Record<string, unknown[]>>,\n): void {\n const blocksFields = getBlocksFields(ctx)\n if (blocksFields.length === 0) return\n\n for (const entity of entities) {\n const eid = entity.id as string\n const entityBlocks = blocksMap.get(eid) ?? {}\n\n for (const { name } of blocksFields) {\n entity[name] = entityBlocks[name] ?? []\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Count cache key\n// ---------------------------------------------------------------------------\n\n/**\n * Build a cache key for a count query.\n * @param prefix - Optional namespace prefix (e.g. 'query' for QueryClient)\n * @param scopeId - Optional scope ID for multi-tenant isolation\n */\nexport function buildCountCacheKey(\n entityName: string,\n where?: SQL,\n prefix?: string,\n scopeId?: string,\n): string {\n let base = prefix ? `${prefix}:${entityName}` : entityName\n if (scopeId) base = `${base}@${scopeId}`\n if (!where) return base\n // Use SQL's toString() representation as a stable key.\n // This is a display string, not executed — safe for cache keying.\n return `${base}:${String(where)}`\n}\n\n// ---------------------------------------------------------------------------\n// ForbiddenError\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a user lacks permission for an entity operation.\n * Consumers (api-handler) catch this and return HTTP 403.\n */\nexport class ForbiddenError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ForbiddenError'\n }\n}\n\n// ---------------------------------------------------------------------------\n// Context helpers — dynamic imports to avoid entity → core circular dep\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Context resolution — framework-agnostic\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the security context from the resolver on EntityContext.\n * Throws ForbiddenError if no resolver is configured or if it returns undefined.\n */\nasync function resolveSecurityContext(\n resolver: ContextResolver | undefined,\n): Promise<SecurityContext> {\n if (!resolver) {\n throw new ForbiddenError(\n 'No context resolver configured on AdminClient/QueryClient. ' +\n 'Use createAdminClient() from @murumets-ee/core/clients, or pass a contextResolver in config.',\n )\n }\n\n const ctx = await resolver()\n\n if (!ctx) {\n throw new ForbiddenError(\n 'Context resolver returned no context. ' +\n 'Ensure auth is configured in your request handler, or use runAsCli() for CLI scripts.',\n )\n }\n\n return ctx\n}\n\n// ---------------------------------------------------------------------------\n// Permission enforcement\n// ---------------------------------------------------------------------------\n\n/**\n * Assert the current user has permission for the given action on the entity.\n * Uses the PermissionChecker from the resolved SecurityContext.\n */\nexport async function assertEntityAccess(\n entity: Entity,\n resolver: ContextResolver | undefined,\n action: 'view' | 'create' | 'update' | 'delete',\n): Promise<void> {\n const ctx = await resolveSecurityContext(resolver)\n\n const role = ctx.user.groups[0]\n if (!role) {\n throw new ForbiddenError(`User '${ctx.user.id}' has no role assigned.`)\n }\n\n if (!ctx.checker(role, entity.name, action)) {\n throw new ForbiddenError(`Forbidden: role '${role}' cannot ${action} '${entity.name}'`)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Scope filtering\n// ---------------------------------------------------------------------------\n\n/**\n * Get the current scope ID for a scoped entity.\n * Returns undefined for global entities.\n */\nexport async function getScopeId(\n entity: Entity,\n resolver: ContextResolver | undefined,\n): Promise<string | undefined> {\n if (!entity.scope || entity.scope === 'global') return undefined\n\n const ctx = await resolveSecurityContext(resolver)\n return ctx.scope?.id\n}\n\n/**\n * Build a WHERE condition for scope filtering.\n */\nexport function buildScopeCondition(ctx: EntityContext, scopeId: string): SQL {\n return eq(ctx.table._scopeId, scopeId)\n}\n\n/**\n * Require scope for a scoped entity. Throws if no scope is in context.\n * Returns undefined for global entities.\n */\nexport async function requireScopeForEntity(\n entity: Entity,\n resolver: ContextResolver | undefined,\n): Promise<string | undefined> {\n if (!entity.scope || entity.scope === 'global') return undefined\n\n const ctx = await resolveSecurityContext(resolver)\n const scopeId = ctx.scope?.id\n\n if (!scopeId) {\n throw new ForbiddenError(\n `Entity '${entity.name}' requires scope '${entity.scope}' but no scope is set in context.`,\n )\n }\n\n return scopeId\n}\n\n// ---------------------------------------------------------------------------\n// Combined auth context resolution (single resolver call)\n// ---------------------------------------------------------------------------\n\n/** Behavior context shape — duplicated locally to avoid importing from behaviors package. */\ninterface BehaviorCtx {\n user?: { id: string; name?: string; email?: string }\n}\n\nexport interface ResolvedAuthContext {\n /** The full SecurityContext returned by the resolver. */\n security: SecurityContext\n /** Scope ID for scoped entities; undefined for global. */\n scopeId: string | undefined\n /** BehaviorContext to thread into lifecycle hooks. */\n behaviorCtx: BehaviorCtx\n}\n\n/**\n * Resolve security context, check permission, derive scope ID, and build\n * BehaviorContext — all from a single resolver invocation.\n *\n * Use instead of calling `assertEntityAccess` + `getScopeId`/`requireScopeForEntity`\n * + manually building a behavior context. Reduces 2-3 resolver calls per write\n * to one, while keeping the granular helpers available for special cases\n * (e.g. cascade delete, which checks permission on a different entity).\n *\n * @param strictScope When true and entity is scoped without a scope in context,\n * throws ForbiddenError. Set on write paths; leave false for\n * reads (callers receive scopeId=undefined and skip filtering).\n */\nexport async function resolveAuthContext(\n entity: Entity,\n resolver: ContextResolver | undefined,\n action: 'view' | 'create' | 'update' | 'delete',\n options?: { strictScope?: boolean },\n): Promise<ResolvedAuthContext> {\n const security = await resolveSecurityContext(resolver)\n\n // Permission check — same logic as assertEntityAccess()\n const role = security.user.groups[0]\n if (!role) {\n throw new ForbiddenError(`User '${security.user.id}' has no role assigned.`)\n }\n if (!security.checker(role, entity.name, action)) {\n throw new ForbiddenError(`Forbidden: role '${role}' cannot ${action} '${entity.name}'`)\n }\n\n // Scope resolution — same logic as getScopeId()/requireScopeForEntity()\n let scopeId: string | undefined\n if (entity.scope && entity.scope !== 'global') {\n scopeId = security.scope?.id\n if (!scopeId && options?.strictScope) {\n throw new ForbiddenError(\n `Entity '${entity.name}' requires scope '${entity.scope}' but no scope is set in context.`,\n )\n }\n }\n\n const behaviorCtx: BehaviorCtx = {\n user: { id: security.user.id, name: security.user.name, email: security.user.email },\n }\n\n return { security, scopeId, behaviorCtx }\n}\n","/**\n * QueryClient - Read-only client for frontend use\n * SAFE for client bundles - NO 'server-only' import\n */\n\nimport { schemaRegistry } from '@murumets-ee/db'\nimport { and, eq, type SQL, sql } from 'drizzle-orm'\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { CountCacheLike } from '../count-cache.js'\nimport type { CursorInput } from '../cursor.js'\nimport { buildCursorCondition } from '../cursor.js'\nimport type { Entity } from '../define-entity.js'\nimport { shapeDto, shapeDtos } from '../dto-shaper.js'\nimport type { FieldConfig } from '../fields/base.js'\nimport {\n attachBlocks,\n buildCountCacheKey,\n buildScopeCondition,\n type ContextResolver,\n type EntityContext,\n getAllFields,\n getBlocksFields,\n loadBlocks,\n mergeTranslations,\n resolveAuthContext,\n} from '../shared/entity-data-ops.js'\nimport type { InferEntityDTO } from '../types/infer.js'\nimport type { Logger } from '../types/logger.js'\n\nexport interface QueryClientConfig<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n entity: Entity<AllFields>\n db: PostgresJsDatabase // Read-only connection (enforced at PostgreSQL level)\n logger?: Logger\n /** Optional count cache for COUNT(*) query optimization. */\n countCache?: CountCacheLike\n /** Resolves the current request's security context. */\n contextResolver?: ContextResolver\n}\n\nexport interface FindByIdOptions {\n select?: string[]\n locale?: string\n /** Default content locale. For localized blocks, NULL rows (from initial create)\n * are only returned as fallback when locale matches defaultLocale. */\n defaultLocale?: string\n}\n\nexport interface FindManyOptions {\n where?: SQL | undefined\n limit?: number\n offset?: number\n orderBy?: SQL | SQL[]\n select?: string[]\n locale?: string\n defaultLocale?: string\n /**\n * Cursor-based (keyset) pagination. When provided, replaces OFFSET with a\n * WHERE condition for O(1) page access at any depth. The `offset` option\n * is ignored when `cursor` is set.\n *\n * The cursor `field` must be a real column on the entity table.\n */\n cursor?: CursorInput\n}\n\nexport interface CountOptions {\n where?: SQL | undefined\n}\n\n/**\n * QueryClient - Read-only entity access for frontends\n *\n * **Requires RequestContext.** All operations check permissions and scope via\n * the context established by `runWithContextAsync()`. CLI scripts use `runAsCli()`.\n *\n * Security & integrity layers:\n * 1. Permission enforcement: `assertEntityAccess()` checks `checker(role, entity, 'view')` from context\n * 2. Scope filtering: scoped entities auto-filter by `_scopeId` from context\n * 3. Publish filtering: publishable entities auto-filter to `status = 'published'`\n * 4. Read-only DB connection (PostgreSQL enforces with `default_transaction_read_only=on`)\n * 5. NO mutation methods on TypeScript type (create/update/delete don't exist)\n *\n * @typeParam AllFields - The entity's complete field map. Inferred automatically\n * when constructing via `createQueryClient(entity)`.\n */\nexport class QueryClient<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n private entity: Entity<AllFields>\n private db: PostgresJsDatabase\n private logger?: Logger\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any> for property access\n private table: PgTableWithColumns<any>\n private isPublishable: boolean\n private countCache?: CountCacheLike\n private contextResolver?: ContextResolver\n\n /** Shared context for entity-data-ops functions. */\n private get ctx(): EntityContext {\n return {\n entity: this.entity,\n db: this.db,\n table: this.table,\n resolveContext: this.contextResolver,\n }\n }\n\n constructor(config: QueryClientConfig<AllFields>) {\n this.entity = config.entity\n this.db = config.db // Assumes read-only connection passed from outside\n this.logger = config.logger\n this.countCache = config.countCache\n this.contextResolver = config.contextResolver\n\n // Detect if entity has publishable behavior\n this.isPublishable = config.entity.behaviors?.some((b) => b.name === 'publishable') ?? false\n\n // Get table from schema registry\n const table = schemaRegistry.get(config.entity.name)\n if (!table) {\n throw new Error(\n `Schema for entity '${config.entity.name}' not found in registry. ` +\n 'Ensure schemas are generated and registered before creating QueryClient.',\n )\n }\n this.table = table\n }\n\n /**\n * Find entity by ID\n * Auto-filters to published if entity has publishable() behavior\n * PHASE 3: Merges translations if locale is provided\n */\n async findById(id: string, options?: FindByIdOptions): Promise<InferEntityDTO<AllFields> | null> {\n this.logger?.info(\n { entity: this.entity.name, id, locale: options?.locale },\n 'Query: Finding entity by ID',\n )\n\n // Permission + scope (one resolver call; reads don't need strict scope)\n const { scopeId } = await resolveAuthContext(this.entity, this.contextResolver, 'view')\n\n // Query database\n const whereConditions = [eq(this.table.id, id)]\n\n // Scope filter\n if (scopeId) whereConditions.push(buildScopeCondition(this.ctx, scopeId))\n\n // Auto-filter to published if entity has publishable behavior\n if (this.isPublishable) {\n whereConditions.push(this.buildPublishFilter(options?.locale))\n }\n\n const [row] = await this.db\n .select()\n .from(this.table)\n .where(and(...whereConditions))\n\n if (!row) return null\n\n // Shape DTO (row is non-null here, so shaped result will be non-null)\n const shaped = shapeDto(this.entity, row, { select: options?.select }) as Record<\n string,\n unknown\n >\n if (!shaped) return null\n\n // Attach blocks from layout table (with locale for block translations)\n if (getBlocksFields(this.ctx).length > 0) {\n const blocksMap = await loadBlocks(this.ctx, [shaped.id as string], options?.locale, {\n defaultLocale: options?.defaultLocale,\n })\n attachBlocks(this.ctx, [shaped], blocksMap)\n }\n\n // PHASE 3: Merge translations if locale specified\n if (options?.locale) {\n const merged = await mergeTranslations(this.ctx, [shaped], options.locale)\n return merged[0] as InferEntityDTO<AllFields>\n }\n\n return shaped as InferEntityDTO<AllFields>\n }\n\n /**\n * Find multiple entities\n * Auto-filters to published if entity has publishable() behavior\n * PHASE 3: Merges translations if locale is provided\n */\n async findMany(options?: FindManyOptions): Promise<InferEntityDTO<AllFields>[]> {\n this.logger?.info(\n { entity: this.entity.name, options, locale: options?.locale },\n 'Query: Finding entities',\n )\n\n // Permission + scope (one resolver call; reads don't need strict scope)\n const { scopeId } = await resolveAuthContext(this.entity, this.contextResolver, 'view')\n\n // Build query\n let query = this.db.select().from(this.table).$dynamic()\n\n // Collect WHERE conditions\n const conditions: SQL[] = []\n\n // Scope filter\n if (scopeId) conditions.push(buildScopeCondition(this.ctx, scopeId))\n\n // Auto-filter to published if entity has publishable behavior\n if (this.isPublishable) {\n conditions.push(this.buildPublishFilter(options?.locale))\n }\n\n if (options?.where) {\n conditions.push(options.where)\n }\n\n // Cursor-based pagination: add keyset WHERE condition (replaces OFFSET)\n if (options?.cursor) {\n // Whitelist: cursor field must be a real column on the entity\n const allFields = getAllFields(this.ctx)\n if (!(options.cursor.field in allFields) && options.cursor.field !== 'id') {\n throw new Error(\n `Invalid cursor field: '${options.cursor.field}' is not a field on '${this.entity.name}'`,\n )\n }\n const cursorCondition = buildCursorCondition(this.table, options.cursor)\n if (cursorCondition) {\n conditions.push(cursorCondition)\n }\n }\n\n if (conditions.length > 0) {\n query = query.where(and(...conditions))\n }\n\n if (options?.limit) {\n query = query.limit(options.limit)\n }\n // Cursor takes precedence over offset — skip offset when cursor is active\n if (options?.offset && !options?.cursor) {\n query = query.offset(options.offset)\n }\n if (options?.orderBy) {\n const cols = Array.isArray(options.orderBy) ? options.orderBy : [options.orderBy]\n query = query.orderBy(...cols)\n }\n\n const rows = await query\n\n // Shape DTOs (filter out null results)\n const shaped = shapeDtos(this.entity, rows, { select: options?.select }).filter(\n (e): e is NonNullable<typeof e> => e !== null,\n ) as Record<string, unknown>[]\n\n // Attach blocks from layout table (with locale for block translations)\n if (getBlocksFields(this.ctx).length > 0 && shaped.length > 0) {\n const entityIds = shaped.map((e) => e.id as string)\n const blocksMap = await loadBlocks(this.ctx, entityIds, options?.locale, {\n defaultLocale: options?.defaultLocale,\n })\n attachBlocks(this.ctx, shaped, blocksMap)\n }\n\n // PHASE 3: Merge translations if locale specified\n if (options?.locale) {\n return (await mergeTranslations(\n this.ctx,\n shaped,\n options.locale,\n )) as InferEntityDTO<AllFields>[]\n }\n\n return shaped as InferEntityDTO<AllFields>[]\n }\n\n /**\n * Count entities\n * Auto-filters to published if entity has publishable() behavior\n */\n async count(options?: CountOptions): Promise<number> {\n this.logger?.info({ entity: this.entity.name, options }, 'Query: Counting entities')\n\n // Permission + scope (one resolver call; reads don't need strict scope)\n const { scopeId } = await resolveAuthContext(this.entity, this.contextResolver, 'view')\n\n // Build cache key: entityName + serialized WHERE (or empty for unfiltered)\n const cacheKey = buildCountCacheKey(this.entity.name, options?.where, 'query', scopeId)\n\n const compute = async (): Promise<number> => {\n let query = this.db.select({ count: sql<number>`count(*)` }).from(this.table).$dynamic()\n // Collect conditions: scope + publish filter + user-provided WHERE\n const conditions: SQL[] = []\n if (scopeId) conditions.push(buildScopeCondition(this.ctx, scopeId))\n if (this.isPublishable) conditions.push(this.buildPublishFilter())\n if (options?.where) conditions.push(options.where)\n if (conditions.length > 0) query = query.where(and(...conditions))\n const [result] = await query\n return Number(result.count)\n }\n\n // No cache configured → run the query directly (back-compat).\n if (!this.countCache) return compute()\n\n // Single-flight: concurrent callers crossing the TTL gap share one query.\n return this.countCache.getOrCompute(cacheKey, compute)\n }\n\n /**\n * Build publish filter SQL condition.\n * When a locale is provided and a locale_status table exists,\n * uses COALESCE to check locale-specific status first, falling back to base status.\n */\n private buildPublishFilter(locale?: string): SQL {\n if (locale) {\n const localeStatusTable = schemaRegistry.get(`${this.entity.name}_locale_status`)\n if (localeStatusTable) {\n return sql`COALESCE(\n (SELECT ${localeStatusTable.status} FROM ${localeStatusTable}\n WHERE ${localeStatusTable.entityId} = ${this.table.id}\n AND ${localeStatusTable.locale} = ${locale}),\n ${this.table.status}\n ) = 'published'`\n }\n }\n return eq(this.table.status, 'published')\n }\n\n // mergeTranslations, getBlocksFields, loadBlocks, attachBlocks, buildCountCacheKey\n // → extracted to ../shared/entity-data-ops.ts (shared with AdminClient)\n\n // NO create/update/delete methods\n // These physically don't exist on the TypeScript type - security by design\n}\n"],"mappings":"0KAwIA,SAAgB,EAAqB,EAAgB,EAAmC,CACtF,IAAM,EAAO,EAAgB,EAAM,CAC7B,EA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I,EAAQ,CACV,IAAM,EAAoB,EAAe,IAAI,GAAG,KAAK,OAAO,KAAK,gBAAgB,CACjF,GAAI,EACF,MAAO,EAAG;oBACE,EAAkB,OAAO,QAAQ,EAAkB;mBACpD,EAAkB,SAAS,KAAK,KAAK,MAAM,GAAG;mBAC9C,EAAkB,OAAO,KAAK,EAAO;YAC5C,KAAK,MAAM,OAAO;yBAI1B,OAAO,EAAG,KAAK,MAAM,OAAQ,YAAY"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/cursor.ts","../../src/dto-shaper.ts","../../src/shared/entity-data-ops.ts","../../src/query/client.ts"],"sourcesContent":["/**\n * Cursor-based (keyset) pagination utilities.\n *\n * Cursor pagination avoids the performance cliff of OFFSET at scale (1M+ rows).\n * Instead of `OFFSET N`, it uses a WHERE condition:\n * `WHERE (sortField < lastValue) OR (sortField = lastValue AND id < lastId)`\n * which Postgres can serve from an index in constant time.\n *\n * The cursor is opaque to the client — base64-encoded JSON.\n *\n * Security:\n * - `field` must be whitelisted against the entity's actual fields\n * - `id` must be a valid UUID\n * - `value` is parameterized (never interpolated into SQL)\n * - Malformed cursors return null (caller returns 400)\n */\n\nimport { and, eq, getTableColumns, gt, lt, or, type SQL } from 'drizzle-orm'\nimport type { PgTable } from 'drizzle-orm/pg-core'\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Cursor input for keyset pagination. */\nexport interface CursorInput {\n /** Sort field name (e.g. 'createdAt'). Must be a real column on the entity. */\n field: string\n /** Last seen value of the sort field. */\n value: string | number\n /** Sort direction — must match the ORDER BY direction. */\n direction: 'asc' | 'desc'\n /** Tie-breaker: last seen entity ID. Required for non-unique sort fields. */\n id?: string | undefined\n}\n\n/** Decoded cursor (internal, after validation). */\ninterface DecodedCursor {\n field: string\n value: string | number\n direction: 'asc' | 'desc'\n id?: string | undefined\n}\n\n// ---------------------------------------------------------------------------\n// UUID validation (same format used throughout the toolkit)\n// ---------------------------------------------------------------------------\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n// ---------------------------------------------------------------------------\n// Encode / decode\n// ---------------------------------------------------------------------------\n\n/**\n * Encode a cursor for API transport (base64url).\n * Built from the last item in a result set.\n */\nexport function encodeCursor(\n item: Record<string, unknown>,\n sortField: string,\n direction: 'asc' | 'desc',\n): string {\n const payload: CursorInput = {\n field: sortField,\n value: item[sortField] as string | number,\n direction,\n id: item.id as string | undefined,\n }\n return btoa(JSON.stringify(payload))\n}\n\n/**\n * Decode and validate a cursor string from query params.\n * Returns null if the cursor is malformed, tampered, or invalid.\n *\n * Security: the `field` value is NOT validated here — the caller must\n * whitelist it against the entity's actual columns.\n */\nexport function decodeCursor(encoded: string): DecodedCursor | null {\n try {\n const json = atob(encoded)\n const parsed: unknown = JSON.parse(json)\n\n if (typeof parsed !== 'object' || parsed === null) return null\n const obj = parsed as Record<string, unknown>\n\n // Validate field\n if (typeof obj.field !== 'string' || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(obj.field)) {\n return null\n }\n\n // Validate value (string or number)\n if (typeof obj.value !== 'string' && typeof obj.value !== 'number') {\n return null\n }\n\n // When the cursor sorts by `id`, the value lands in a UUID-typed\n // column. Reject non-UUID strings here so the caller doesn't surface\n // a Postgres cast error (and side-channel \"valid format vs invalid\n // format\") on the next request.\n if (obj.field === 'id' && (typeof obj.value !== 'string' || !UUID_RE.test(obj.value))) {\n return null\n }\n\n // Validate direction\n if (obj.direction !== 'asc' && obj.direction !== 'desc') {\n return null\n }\n\n // Validate id (optional, must be UUID if present)\n if (obj.id !== undefined) {\n if (typeof obj.id !== 'string' || !UUID_RE.test(obj.id)) {\n return null\n }\n }\n\n return {\n field: obj.field,\n value: obj.value,\n direction: obj.direction,\n id: obj.id as string | undefined,\n }\n } catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// SQL condition builder\n// ---------------------------------------------------------------------------\n\n/**\n * Build the keyset WHERE condition from a decoded cursor.\n *\n * For DESC: `WHERE (field < value) OR (field = value AND id < cursorId)`\n * For ASC: `WHERE (field > value) OR (field = value AND id > cursorId)`\n *\n * The caller must verify that `cursor.field` exists on the table before calling.\n *\n * @param table - Drizzle table with columns\n * @param cursor - Decoded and validated cursor\n * @returns SQL condition, or null if the field doesn't exist on the table\n */\nexport function buildCursorCondition(table: PgTable, cursor: DecodedCursor): SQL | null {\n const cols = getTableColumns(table)\n const column = cols[cursor.field]\n if (!column) return null\n\n const isDesc = cursor.direction === 'desc'\n const compare = isDesc ? lt : gt\n\n // Primary condition: sort field passes the cursor value\n const fieldCondition = compare(column, cursor.value)\n\n // Without tie-breaker ID, use simple comparison\n if (!cursor.id) {\n return fieldCondition\n }\n\n // With tie-breaker: (field < value) OR (field = value AND id < cursorId)\n const idColumn = cols.id\n if (!idColumn) return fieldCondition\n\n const idCondition = compare(idColumn, cursor.id)\n // Drizzle's `or`/`and` return SQL when called with at least one defined arg.\n // Fall back to fieldCondition rather than asserting non-null.\n return or(fieldCondition, and(eq(column, cursor.value), idCondition)) ?? fieldCondition\n}\n","/**\n * DTO Shaper\n * Transforms raw DB rows into clean DTOs.\n * All fields are real columns — just read from row directly.\n */\n\nimport type { Entity } from './define-entity.js'\nimport type { FieldConfig } from './fields/base.js'\nimport type { InferEntityDTO } from './types/infer.js'\n\nexport interface ShapeDtoOptions {\n /** Explicit field selection. */\n select?: string[] | undefined\n /**\n * Include internal fields in the output. Two rules apply:\n * 1. Fields marked `internal: true` in their config (the canonical flag).\n * 2. Legacy infrastructure columns whose name starts with `_` and are not\n * declared in `entity.allFields` (e.g. `_version`, `_scopeId` added by\n * the schema generator).\n *\n * Set this on trusted server reads that need to inspect or transition\n * state-machine fields (e.g. the workflow route reading the current\n * `_workflowStatus` before deciding the next state).\n */\n includeInternal?: boolean | undefined\n}\n\n/**\n * Shape a raw DB row into a typed DTO.\n * Every field is a real column — read directly from row.\n */\nexport function shapeDto<AllFields extends Record<string, FieldConfig>>(\n entity: Entity<AllFields>,\n row: Record<string, unknown>,\n options?: ShapeDtoOptions,\n): InferEntityDTO<AllFields> | null {\n if (!row) return null\n\n const result: Record<string, unknown> = {}\n const fieldsToInclude = options?.select || Object.keys(entity.allFields)\n\n for (const fieldName of fieldsToInclude) {\n const fieldConfig = (entity.allFields as Record<string, FieldConfig>)[fieldName]\n\n if (!options?.includeInternal) {\n // Two complementary internal-field rules, both bypassed by `includeInternal`:\n // 1. Naming convention: any field whose name starts with `_` (legacy\n // infrastructure columns like `_version`, `_scopeId`, plus any\n // `_workflowStatus`-style behavior field).\n // 2. Explicit flag: `internal: true` on the field config (the canonical\n // flag — works for fields that don't follow the underscore convention).\n const internalByName = fieldName.startsWith('_')\n const internalByFlag = fieldConfig?.internal === true\n if (internalByName || internalByFlag) continue\n }\n\n if (!fieldConfig) continue\n\n // Blocks are loaded separately from layout tables\n if (fieldConfig.type === 'blocks') continue\n\n result[fieldName] = row[fieldName]\n }\n\n return result as InferEntityDTO<AllFields>\n}\n\n/**\n * Shape multiple rows\n */\nexport function shapeDtos<AllFields extends Record<string, FieldConfig>>(\n entity: Entity<AllFields>,\n rows: Record<string, unknown>[],\n options?: ShapeDtoOptions,\n): (InferEntityDTO<AllFields> | null)[] {\n return rows.map((row) => shapeDto(entity, row, options))\n}\n","/**\n * Shared entity data operations.\n *\n * Extracted from AdminClient and QueryClient to eliminate duplication.\n * These are standalone functions that take an EntityContext — both clients\n * satisfy this interface via `this`.\n */\n\nimport { schemaRegistry } from '@murumets-ee/db'\nimport { and, eq, inArray, isNull, or, type SQL } from 'drizzle-orm'\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { BehaviorContext } from '../behaviors/types.js'\nimport type { Entity } from '../define-entity.js'\nimport type { FieldConfig } from '../fields/base.js'\n\n// ---------------------------------------------------------------------------\n// Context interface — satisfied by both AdminClient and QueryClient via `this`\n// ---------------------------------------------------------------------------\n\n/**\n * Security context resolved per-request. Provided by the consumer\n * (e.g., via React.cache() in Next.js, or runAsCli for CLI).\n * The entity package has zero knowledge of how this is resolved.\n */\nexport interface SecurityContext {\n user: { id: string; groups: string[]; name?: string; email?: string }\n checker: (role: string, resource: string, action: string) => boolean\n scope?: { type: string; id: string }\n}\n\n/**\n * Function that resolves the current request's security context.\n * Injected at construction time — the entity package never imports\n * @murumets-ee/core or any framework-specific code.\n *\n * Returns undefined only when intentionally skipping enforcement\n * (should not happen in production — throw ForbiddenError instead).\n */\nexport type ContextResolver = () =>\n | SecurityContext\n | undefined\n | Promise<SecurityContext | undefined>\n\nexport interface EntityContext {\n entity: Entity\n db: PostgresJsDatabase\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any>\n table: PgTableWithColumns<any>\n /** Resolves the current request's security context. */\n resolveContext?: ContextResolver | undefined\n}\n\n// ---------------------------------------------------------------------------\n// Field accessors\n// ---------------------------------------------------------------------------\n\n/** Get the entity's full field map with proper typing. Eliminates repeated casts. */\nexport function getAllFields(ctx: EntityContext): Record<string, FieldConfig> {\n return ctx.entity.allFields as Record<string, FieldConfig>\n}\n\n/** Get all blocks field definitions for this entity. */\nexport function getBlocksFields(ctx: EntityContext): Array<{ name: string; config: FieldConfig }> {\n return Object.entries(getAllFields(ctx))\n .filter(([_, config]) => config.type === 'blocks')\n .map(([name, config]) => ({ name, config }))\n}\n\n// ---------------------------------------------------------------------------\n// Translation merging\n// ---------------------------------------------------------------------------\n\n/**\n * Merge translations into entities for the specified locale.\n * Reads translatable field values from real columns on the translation row.\n */\nexport async function mergeTranslations<T extends Record<string, unknown>>(\n ctx: EntityContext,\n entities: T[],\n locale: string,\n): Promise<T[]> {\n if (!entities.length) return entities\n\n const translationTableName = `${ctx.entity.name}_translations`\n const translationTable = schemaRegistry.get(translationTableName)\n\n if (!translationTable) return entities\n\n const entityIds = entities.map((e) => e.id)\n\n const translations = await ctx.db\n .select()\n .from(translationTable)\n .where(and(inArray(translationTable.entityId, entityIds), eq(translationTable.locale, locale)))\n\n // Get translatable field names\n const translatableFields = Object.entries(getAllFields(ctx))\n .filter(([_, config]) => config.translatable)\n .map(([name]) => name)\n\n const translationMap = new Map<unknown, Record<string, unknown>>()\n for (const translation of translations) {\n const translatedValues: Record<string, unknown> = {}\n for (const fieldName of translatableFields) {\n const value = (translation as Record<string, unknown>)[fieldName]\n if (value !== undefined && value !== null) {\n translatedValues[fieldName] = value\n }\n }\n translationMap.set(translation.entityId, translatedValues)\n }\n\n return entities.map((entity) => {\n const translatedFields = translationMap.get(entity.id)\n if (!translatedFields) return entity\n return { ...entity, ...translatedFields }\n })\n}\n\n// ---------------------------------------------------------------------------\n// Block loading\n// ---------------------------------------------------------------------------\n\nexport interface LoadBlocksOptions {\n defaultLocale?: string | undefined\n /**\n * When true (admin editing), clears untranslated translatable block fields\n * to empty string — signals incomplete translation in the editing UI.\n * When false (visitor-facing), preserves base data as fallback.\n */\n strictTranslations?: boolean | undefined\n}\n\n/**\n * Load blocks for one or more entities from the layout table.\n *\n * Handles both block translation modes:\n * - Shared layout (localized: false): loads locale=NULL rows, merges translations\n * - Per-locale layout (localized: true): loads rows matching the provided locale only\n */\nexport async function loadBlocks(\n ctx: EntityContext,\n entityIds: string[],\n locale?: string,\n options?: LoadBlocksOptions,\n): Promise<Map<string, Record<string, unknown[]>>> {\n const blocksFields = getBlocksFields(ctx)\n if (blocksFields.length === 0 || entityIds.length === 0) {\n return new Map()\n }\n\n const layoutTable = schemaRegistry.get(`${ctx.entity.name}_layout`)\n if (!layoutTable) return new Map()\n\n // Determine block field modes\n const sharedFields = blocksFields.filter(\n ({ config }) => !('localized' in config && config.localized),\n )\n const localizedFields = blocksFields.filter(\n ({ config }) => 'localized' in config && config.localized,\n )\n\n const result = new Map<string, Record<string, unknown[]>>()\n\n // ---- Shared blocks: locale IS NULL, translations from layout_translations ----\n if (sharedFields.length > 0) {\n const rows = await ctx.db\n .select()\n .from(layoutTable)\n .where(and(inArray(layoutTable.entityId, entityIds), isNull(layoutTable.locale)))\n .orderBy(layoutTable.sortOrder)\n\n // Load translations if locale provided\n let blockTransMap: Map<string, Record<string, unknown>> | undefined\n if (locale && rows.length > 0) {\n const layoutTransTable = schemaRegistry.get(`${ctx.entity.name}_layout_translations`)\n if (layoutTransTable) {\n const layoutIds = rows.map((r) => r.id as string)\n const translations = await ctx.db\n .select()\n .from(layoutTransTable)\n .where(\n and(inArray(layoutTransTable.layoutId, layoutIds), eq(layoutTransTable.locale, locale)),\n )\n\n blockTransMap = new Map()\n for (const t of translations) {\n blockTransMap.set(t.layoutId as string, (t.fields as Record<string, unknown>) ?? {})\n }\n }\n }\n\n // Build block definition lookup for translatable field clearing (strict mode only)\n let blockDefMap: Map<string, Record<string, FieldConfig>> | undefined\n if (options?.strictTranslations) {\n blockDefMap = new Map()\n for (const { config } of sharedFields) {\n if (config.type !== 'blocks') continue\n for (const def of config.blocks) {\n blockDefMap.set(def.slug, def.fields)\n }\n }\n }\n\n for (const row of rows) {\n const eid = row.entityId as string\n const fname = row.fieldName as string\n\n let entityBlocks = result.get(eid)\n if (!entityBlocks) {\n entityBlocks = {}\n result.set(eid, entityBlocks)\n }\n if (!entityBlocks[fname]) entityBlocks[fname] = []\n\n const blockData = (row.data as Record<string, unknown>) ?? {}\n const translatedFields = blockTransMap?.get(row.id as string)\n\n // Build the block object\n const block: Record<string, unknown> = {\n _block: row.blockType,\n _id: row.id,\n ...blockData,\n ...(translatedFields ?? {}),\n }\n\n // Strict mode: clear untranslated translatable fields when loading for non-default locale\n if (locale && blockDefMap) {\n const blockType = row.blockType as string\n const fieldDefs = blockDefMap.get(blockType)\n if (fieldDefs) {\n for (const [fieldName, fieldConfig] of Object.entries(fieldDefs)) {\n if (fieldConfig.translatable && !translatedFields?.[fieldName]) {\n block[fieldName] = ''\n }\n }\n }\n }\n\n entityBlocks[fname].push(block)\n }\n }\n\n // ---- Localized blocks: filter by locale column ----\n // NULL rows (from initial create) only fall back for the default locale.\n // Non-default locales without locale-specific rows get an empty array.\n if (localizedFields.length > 0) {\n const isDefault = !locale || locale === options?.defaultLocale\n let localeCondition: SQL\n if (locale) {\n if (isDefault) {\n // Both args defined → drizzle's `or` always returns SQL; fall back defensively\n localeCondition =\n or(eq(layoutTable.locale, locale), isNull(layoutTable.locale)) ??\n eq(layoutTable.locale, locale)\n } else {\n localeCondition = eq(layoutTable.locale, locale)\n }\n } else {\n localeCondition = isNull(layoutTable.locale)\n }\n\n const rows = await ctx.db\n .select()\n .from(layoutTable)\n .where(and(inArray(layoutTable.entityId, entityIds), localeCondition))\n .orderBy(layoutTable.sortOrder)\n\n // Group by entityId + fieldName, prefer locale-specific rows over NULL\n const grouped = new Map<string, { localeRows: typeof rows; nullRows: typeof rows }>()\n for (const row of rows) {\n const key = `${row.entityId}::${row.fieldName}`\n let group = grouped.get(key)\n if (!group) {\n group = { localeRows: [], nullRows: [] }\n grouped.set(key, group)\n }\n if (row.locale) {\n group.localeRows.push(row)\n } else {\n group.nullRows.push(row)\n }\n }\n\n for (const [, { localeRows, nullRows }] of grouped) {\n // Use locale-specific rows if available, otherwise fall back to NULL\n const effective = localeRows.length > 0 ? localeRows : nullRows\n\n for (const row of effective) {\n const eid = row.entityId as string\n const fname = row.fieldName as string\n\n let entityBlocks = result.get(eid)\n if (!entityBlocks) {\n entityBlocks = {}\n result.set(eid, entityBlocks)\n }\n if (!entityBlocks[fname]) entityBlocks[fname] = []\n\n const blockData = (row.data as Record<string, unknown>) ?? {}\n\n entityBlocks[fname].push({\n _block: row.blockType,\n _id: row.id,\n ...blockData,\n })\n }\n }\n }\n\n return result\n}\n\n/**\n * Attach loaded blocks to shaped DTOs.\n */\nexport function attachBlocks(\n ctx: EntityContext,\n entities: Record<string, unknown>[],\n blocksMap: Map<string, Record<string, unknown[]>>,\n): void {\n const blocksFields = getBlocksFields(ctx)\n if (blocksFields.length === 0) return\n\n for (const entity of entities) {\n const eid = entity.id as string\n const entityBlocks = blocksMap.get(eid) ?? {}\n\n for (const { name } of blocksFields) {\n entity[name] = entityBlocks[name] ?? []\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Count cache key\n// ---------------------------------------------------------------------------\n\n/**\n * Build a cache key for a count query.\n * @param prefix - Optional namespace prefix (e.g. 'query' for QueryClient)\n * @param scopeId - Optional scope ID for multi-tenant isolation\n */\nexport function buildCountCacheKey(\n entityName: string,\n where?: SQL,\n prefix?: string,\n scopeId?: string,\n): string {\n let base = prefix ? `${prefix}:${entityName}` : entityName\n if (scopeId) base = `${base}@${scopeId}`\n if (!where) return base\n // Use SQL's toString() representation as a stable key.\n // This is a display string, not executed — safe for cache keying.\n return `${base}:${String(where)}`\n}\n\n// ---------------------------------------------------------------------------\n// ForbiddenError\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a user lacks permission for an entity operation.\n * Consumers (api-handler) catch this and return HTTP 403.\n */\nexport class ForbiddenError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ForbiddenError'\n }\n}\n\n// ---------------------------------------------------------------------------\n// Context helpers — dynamic imports to avoid entity → core circular dep\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Context resolution — framework-agnostic\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the security context from the resolver on EntityContext.\n * Throws ForbiddenError if no resolver is configured or if it returns undefined.\n */\nasync function resolveSecurityContext(\n resolver: ContextResolver | undefined,\n): Promise<SecurityContext> {\n if (!resolver) {\n throw new ForbiddenError(\n 'No context resolver configured on AdminClient/QueryClient. ' +\n 'Use createAdminClient() from @murumets-ee/core/clients, or pass a contextResolver in config.',\n )\n }\n\n const ctx = await resolver()\n\n if (!ctx) {\n throw new ForbiddenError(\n 'Context resolver returned no context. ' +\n 'Ensure auth is configured in your request handler, or use runAsCli() for CLI scripts.',\n )\n }\n\n return ctx\n}\n\n// ---------------------------------------------------------------------------\n// Permission enforcement\n// ---------------------------------------------------------------------------\n\n/**\n * Assert the current user has permission for the given action on the entity.\n * Uses the PermissionChecker from the resolved SecurityContext.\n */\nexport async function assertEntityAccess(\n entity: Entity,\n resolver: ContextResolver | undefined,\n action: 'view' | 'create' | 'update' | 'delete',\n): Promise<void> {\n const ctx = await resolveSecurityContext(resolver)\n\n const role = ctx.user.groups[0]\n if (!role) {\n throw new ForbiddenError(`User '${ctx.user.id}' has no role assigned.`)\n }\n\n if (!ctx.checker(role, entity.name, action)) {\n throw new ForbiddenError(`Forbidden: role '${role}' cannot ${action} '${entity.name}'`)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Scope filtering\n// ---------------------------------------------------------------------------\n\n/**\n * Get the current scope ID for a scoped entity.\n * Returns undefined for global entities.\n */\nexport async function getScopeId(\n entity: Entity,\n resolver: ContextResolver | undefined,\n): Promise<string | undefined> {\n if (!entity.scope || entity.scope === 'global') return undefined\n\n const ctx = await resolveSecurityContext(resolver)\n return ctx.scope?.id\n}\n\n/**\n * Build a WHERE condition for scope filtering.\n */\nexport function buildScopeCondition(ctx: EntityContext, scopeId: string): SQL {\n return eq(ctx.table._scopeId, scopeId)\n}\n\n/**\n * Require scope for a scoped entity. Throws if no scope is in context.\n * Returns undefined for global entities.\n */\nexport async function requireScopeForEntity(\n entity: Entity,\n resolver: ContextResolver | undefined,\n): Promise<string | undefined> {\n if (!entity.scope || entity.scope === 'global') return undefined\n\n const ctx = await resolveSecurityContext(resolver)\n const scopeId = ctx.scope?.id\n\n if (!scopeId) {\n throw new ForbiddenError(\n `Entity '${entity.name}' requires scope '${entity.scope}' but no scope is set in context.`,\n )\n }\n\n return scopeId\n}\n\n// ---------------------------------------------------------------------------\n// Combined auth context resolution (single resolver call)\n// ---------------------------------------------------------------------------\n\nexport interface ResolvedAuthContext {\n /** The full SecurityContext returned by the resolver. */\n security: SecurityContext\n /** Scope ID for scoped entities; undefined for global. */\n scopeId: string | undefined\n /** BehaviorContext to thread into lifecycle hooks. */\n behaviorCtx: BehaviorContext\n}\n\n/**\n * Resolve security context, check permission, derive scope ID, and build\n * BehaviorContext — all from a single resolver invocation.\n *\n * Use instead of calling `assertEntityAccess` + `getScopeId`/`requireScopeForEntity`\n * + manually building a behavior context. Reduces 2-3 resolver calls per write\n * to one, while keeping the granular helpers available for special cases\n * (e.g. cascade delete, which checks permission on a different entity).\n *\n * @param strictScope When true and entity is scoped without a scope in context,\n * throws ForbiddenError. Set on write paths; leave false for\n * reads (callers receive scopeId=undefined and skip filtering).\n * @param enqueueOnCommit Resolved enqueue function from\n * `AdminClientConfig.enqueueOnCommit`. When provided, this\n * is set on `behaviorCtx.enqueueOnCommit` so projection\n * behaviors can fire jobs without importing the queue\n * package. PR C of PLAN-OUTBOX.\n */\nexport async function resolveAuthContext(\n entity: Entity,\n resolver: ContextResolver | undefined,\n action: 'view' | 'create' | 'update' | 'delete',\n options?: {\n strictScope?: boolean\n enqueueOnCommit?: BehaviorContext['enqueueOnCommit']\n },\n): Promise<ResolvedAuthContext> {\n const security = await resolveSecurityContext(resolver)\n\n // Permission check — same logic as assertEntityAccess()\n const role = security.user.groups[0]\n if (!role) {\n throw new ForbiddenError(`User '${security.user.id}' has no role assigned.`)\n }\n if (!security.checker(role, entity.name, action)) {\n throw new ForbiddenError(`Forbidden: role '${role}' cannot ${action} '${entity.name}'`)\n }\n\n // Scope resolution — same logic as getScopeId()/requireScopeForEntity()\n let scopeId: string | undefined\n if (entity.scope && entity.scope !== 'global') {\n scopeId = security.scope?.id\n if (!scopeId && options?.strictScope) {\n throw new ForbiddenError(\n `Entity '${entity.name}' requires scope '${entity.scope}' but no scope is set in context.`,\n )\n }\n }\n\n const behaviorCtx: BehaviorContext = {\n user: {\n id: security.user.id,\n ...(security.user.name !== undefined && { name: security.user.name }),\n ...(security.user.email !== undefined && { email: security.user.email }),\n },\n ...(options?.enqueueOnCommit !== undefined && { enqueueOnCommit: options.enqueueOnCommit }),\n }\n\n return { security, scopeId, behaviorCtx }\n}\n","/**\n * QueryClient - Read-only client for frontend use\n * SAFE for client bundles - NO 'server-only' import\n */\n\nimport { schemaRegistry } from '@murumets-ee/db'\nimport { and, eq, type SQL, sql } from 'drizzle-orm'\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { CountCacheLike } from '../count-cache.js'\nimport type { CursorInput } from '../cursor.js'\nimport { buildCursorCondition } from '../cursor.js'\nimport type { Entity } from '../define-entity.js'\nimport { shapeDto, shapeDtos } from '../dto-shaper.js'\nimport type { FieldConfig } from '../fields/base.js'\nimport {\n attachBlocks,\n buildCountCacheKey,\n buildScopeCondition,\n type ContextResolver,\n type EntityContext,\n getAllFields,\n getBlocksFields,\n loadBlocks,\n mergeTranslations,\n resolveAuthContext,\n} from '../shared/entity-data-ops.js'\nimport type { InferEntityDTO } from '../types/infer.js'\nimport type { Logger } from '../types/logger.js'\n\nexport interface QueryClientConfig<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n entity: Entity<AllFields>\n db: PostgresJsDatabase // Read-only connection (enforced at PostgreSQL level)\n logger?: Logger | undefined\n /** Optional count cache for COUNT(*) query optimization. */\n countCache?: CountCacheLike | undefined\n /** Resolves the current request's security context. */\n contextResolver?: ContextResolver | undefined\n}\n\nexport interface FindByIdOptions {\n select?: string[]\n locale?: string | undefined\n /** Default content locale. For localized blocks, NULL rows (from initial create)\n * are only returned as fallback when locale matches defaultLocale. */\n defaultLocale?: string | undefined\n}\n\nexport interface FindManyOptions {\n where?: SQL | undefined\n limit?: number | undefined\n offset?: number | undefined\n orderBy?: SQL | SQL[] | undefined\n select?: string[] | undefined\n locale?: string | undefined\n defaultLocale?: string | undefined\n /**\n * Cursor-based (keyset) pagination. When provided, replaces OFFSET with a\n * WHERE condition for O(1) page access at any depth. The `offset` option\n * is ignored when `cursor` is set.\n *\n * The cursor `field` must be a real column on the entity table.\n */\n cursor?: CursorInput | undefined\n}\n\nexport interface CountOptions {\n where?: SQL | undefined\n}\n\n/**\n * QueryClient - Read-only entity access for frontends\n *\n * **Requires RequestContext.** All operations check permissions and scope via\n * the context established by `runWithContextAsync()`. CLI scripts use `runAsCli()`.\n *\n * Security & integrity layers:\n * 1. Permission enforcement: `assertEntityAccess()` checks `checker(role, entity, 'view')` from context\n * 2. Scope filtering: scoped entities auto-filter by `_scopeId` from context\n * 3. Publish filtering: publishable entities auto-filter to `status = 'published'`\n * 4. Read-only DB connection (PostgreSQL enforces with `default_transaction_read_only=on`)\n * 5. NO mutation methods on TypeScript type (create/update/delete don't exist)\n *\n * @typeParam AllFields - The entity's complete field map. Inferred automatically\n * when constructing via `createQueryClient(entity)`.\n */\nexport class QueryClient<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n private entity: Entity<AllFields>\n private db: PostgresJsDatabase\n private logger?: Logger | undefined\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any> for property access\n private table: PgTableWithColumns<any>\n private isPublishable: boolean\n private countCache?: CountCacheLike | undefined\n private contextResolver?: ContextResolver | undefined\n\n /** Shared context for entity-data-ops functions. */\n private get ctx(): EntityContext {\n return {\n entity: this.entity,\n db: this.db,\n table: this.table,\n resolveContext: this.contextResolver,\n }\n }\n\n constructor(config: QueryClientConfig<AllFields>) {\n this.entity = config.entity\n this.db = config.db // Assumes read-only connection passed from outside\n this.logger = config.logger\n this.countCache = config.countCache\n this.contextResolver = config.contextResolver\n\n // Detect if entity has publishable behavior\n this.isPublishable = config.entity.behaviors?.some((b) => b.name === 'publishable') ?? false\n\n // Get table from schema registry\n const table = schemaRegistry.get(config.entity.name)\n if (!table) {\n throw new Error(\n `Schema for entity '${config.entity.name}' not found in registry. ` +\n 'Ensure schemas are generated and registered before creating QueryClient.',\n )\n }\n this.table = table\n }\n\n /**\n * Find entity by ID\n * Auto-filters to published if entity has publishable() behavior\n * PHASE 3: Merges translations if locale is provided\n */\n async findById(id: string, options?: FindByIdOptions): Promise<InferEntityDTO<AllFields> | null> {\n this.logger?.info(\n { entity: this.entity.name, id, locale: options?.locale },\n 'Query: Finding entity by ID',\n )\n\n // Permission + scope (one resolver call; reads don't need strict scope)\n const { scopeId } = await resolveAuthContext(this.entity, this.contextResolver, 'view')\n\n // Query database\n const whereConditions = [eq(this.table.id, id)]\n\n // Scope filter\n if (scopeId) whereConditions.push(buildScopeCondition(this.ctx, scopeId))\n\n // Auto-filter to published if entity has publishable behavior\n if (this.isPublishable) {\n whereConditions.push(this.buildPublishFilter(options?.locale))\n }\n\n const [row] = await this.db\n .select()\n .from(this.table)\n .where(and(...whereConditions))\n\n if (!row) return null\n\n // Shape DTO (row is non-null here, so shaped result will be non-null)\n const shaped = shapeDto(this.entity, row, { select: options?.select }) as Record<\n string,\n unknown\n >\n if (!shaped) return null\n\n // Attach blocks from layout table (with locale for block translations)\n if (getBlocksFields(this.ctx).length > 0) {\n const blocksMap = await loadBlocks(this.ctx, [shaped.id as string], options?.locale, {\n defaultLocale: options?.defaultLocale,\n })\n attachBlocks(this.ctx, [shaped], blocksMap)\n }\n\n // PHASE 3: Merge translations if locale specified\n if (options?.locale) {\n const merged = await mergeTranslations(this.ctx, [shaped], options.locale)\n return merged[0] as InferEntityDTO<AllFields>\n }\n\n return shaped as InferEntityDTO<AllFields>\n }\n\n /**\n * Find multiple entities\n * Auto-filters to published if entity has publishable() behavior\n * PHASE 3: Merges translations if locale is provided\n */\n async findMany(options?: FindManyOptions): Promise<InferEntityDTO<AllFields>[]> {\n this.logger?.info(\n { entity: this.entity.name, options, locale: options?.locale },\n 'Query: Finding entities',\n )\n\n // Permission + scope (one resolver call; reads don't need strict scope)\n const { scopeId } = await resolveAuthContext(this.entity, this.contextResolver, 'view')\n\n // Build query\n let query = this.db.select().from(this.table).$dynamic()\n\n // Collect WHERE conditions\n const conditions: SQL[] = []\n\n // Scope filter\n if (scopeId) conditions.push(buildScopeCondition(this.ctx, scopeId))\n\n // Auto-filter to published if entity has publishable behavior\n if (this.isPublishable) {\n conditions.push(this.buildPublishFilter(options?.locale))\n }\n\n if (options?.where) {\n conditions.push(options.where)\n }\n\n // Cursor-based pagination: add keyset WHERE condition (replaces OFFSET)\n if (options?.cursor) {\n // Whitelist: cursor field must be a real column on the entity.\n // `Object.hasOwn` (vs the `in` operator) rejects prototype-chain keys\n // like `__proto__` / `constructor` / `toString`.\n const allFields = getAllFields(this.ctx)\n if (!Object.hasOwn(allFields, options.cursor.field) && options.cursor.field !== 'id') {\n throw new Error(\n `Invalid cursor field: '${options.cursor.field}' is not a field on '${this.entity.name}'`,\n )\n }\n const cursorCondition = buildCursorCondition(this.table, options.cursor)\n if (cursorCondition) {\n conditions.push(cursorCondition)\n }\n }\n\n if (conditions.length > 0) {\n query = query.where(and(...conditions))\n }\n\n if (options?.limit) {\n query = query.limit(options.limit)\n }\n // Cursor takes precedence over offset — skip offset when cursor is active\n if (options?.offset && !options?.cursor) {\n query = query.offset(options.offset)\n }\n if (options?.orderBy) {\n const cols = Array.isArray(options.orderBy) ? options.orderBy : [options.orderBy]\n query = query.orderBy(...cols)\n }\n\n const rows = await query\n\n // Shape DTOs (filter out null results)\n const shaped = shapeDtos(this.entity, rows, { select: options?.select }).filter(\n (e): e is NonNullable<typeof e> => e !== null,\n ) as Record<string, unknown>[]\n\n // Attach blocks from layout table (with locale for block translations)\n if (getBlocksFields(this.ctx).length > 0 && shaped.length > 0) {\n const entityIds = shaped.map((e) => e.id as string)\n const blocksMap = await loadBlocks(this.ctx, entityIds, options?.locale, {\n defaultLocale: options?.defaultLocale,\n })\n attachBlocks(this.ctx, shaped, blocksMap)\n }\n\n // PHASE 3: Merge translations if locale specified\n if (options?.locale) {\n return (await mergeTranslations(\n this.ctx,\n shaped,\n options.locale,\n )) as InferEntityDTO<AllFields>[]\n }\n\n return shaped as InferEntityDTO<AllFields>[]\n }\n\n /**\n * Count entities\n * Auto-filters to published if entity has publishable() behavior\n */\n async count(options?: CountOptions): Promise<number> {\n this.logger?.info({ entity: this.entity.name, options }, 'Query: Counting entities')\n\n // Permission + scope (one resolver call; reads don't need strict scope)\n const { scopeId } = await resolveAuthContext(this.entity, this.contextResolver, 'view')\n\n // Build cache key: entityName + serialized WHERE (or empty for unfiltered)\n const cacheKey = buildCountCacheKey(this.entity.name, options?.where, 'query', scopeId)\n\n const compute = async (): Promise<number> => {\n let query = this.db.select({ count: sql<number>`count(*)` }).from(this.table).$dynamic()\n // Collect conditions: scope + publish filter + user-provided WHERE\n const conditions: SQL[] = []\n if (scopeId) conditions.push(buildScopeCondition(this.ctx, scopeId))\n if (this.isPublishable) conditions.push(this.buildPublishFilter())\n if (options?.where) conditions.push(options.where)\n if (conditions.length > 0) query = query.where(and(...conditions))\n const [result] = await query\n if (!result) throw new Error(`count query returned no row for ${this.entity.name}`)\n return Number(result.count)\n }\n\n // No cache configured → run the query directly (back-compat).\n if (!this.countCache) return compute()\n\n // Single-flight: concurrent callers crossing the TTL gap share one query.\n return this.countCache.getOrCompute(cacheKey, compute)\n }\n\n /**\n * Build publish filter SQL condition.\n * When a locale is provided and a locale_status table exists,\n * uses COALESCE to check locale-specific status first, falling back to base status.\n */\n private buildPublishFilter(locale?: string): SQL {\n if (locale) {\n const localeStatusTable = schemaRegistry.get(`${this.entity.name}_locale_status`)\n if (localeStatusTable) {\n return sql`COALESCE(\n (SELECT ${localeStatusTable.status} FROM ${localeStatusTable}\n WHERE ${localeStatusTable.entityId} = ${this.table.id}\n AND ${localeStatusTable.locale} = ${locale}),\n ${this.table.status}\n ) = 'published'`\n }\n }\n return eq(this.table.status, 'published')\n }\n\n // mergeTranslations, getBlocksFields, loadBlocks, attachBlocks, buildCountCacheKey\n // → extracted to ../shared/entity-data-ops.ts (shared with AdminClient)\n\n // NO create/update/delete methods\n // These physically don't exist on the TypeScript type - security by design\n}\n"],"mappings":"0KAgJA,SAAgB,EAAqB,EAAgB,EAAmC,CACtF,IAAM,EAAO,EAAgB,EAAM,CAC7B,EAAS,EAAK,EAAO,OAC3B,GAAI,CAAC,EAAQ,OAAO,KAGpB,IAAM,EADS,EAAO,YAAc,OACX,EAAK,EAGxB,EAAiB,EAAQ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AAU,MAAM,EACvB,GAAI,CAAC,EAAQ,MAAU,MAAM,mCAAmC,KAAK,OAAO,OAAO,CACnF,OAAO,OAAO,EAAO,MAAM,EAO7B,OAHK,KAAK,WAGH,KAAK,WAAW,aAAa,EAAU,EAAQ,CAHzB,GAAS,CAWxC,mBAA2B,EAAsB,CAC/C,GAAI,EAAQ,CACV,IAAM,EAAoB,EAAe,IAAI,GAAG,KAAK,OAAO,KAAK,gBAAgB,CACjF,GAAI,EACF,MAAO,EAAG;oBACE,EAAkB,OAAO,QAAQ,EAAkB;mBACpD,EAAkB,SAAS,KAAK,KAAK,MAAM,GAAG;mBAC9C,EAAkB,OAAO,KAAK,EAAO;YAC5C,KAAK,MAAM,OAAO;yBAI1B,OAAO,EAAG,KAAK,MAAM,OAAQ,YAAY"}
@@ -36,6 +36,23 @@ interface BaseFieldConfig {
36
36
  translatable?: boolean;
37
37
  indexed?: boolean;
38
38
  unique?: boolean;
39
+ /**
40
+ * Marks the field as **system-managed**: stored as a real column, populated
41
+ * by behavior hooks or trusted server-side transitions, but NOT writable
42
+ * through the public `AdminClient.create/update` surface.
43
+ *
44
+ * - Caller-supplied values for internal fields are silently stripped before
45
+ * hooks run (so an HTTP PATCH cannot poison a workflow state).
46
+ * - `beforeCreate` / `beforeUpdate` hooks may still set them (they run after
47
+ * the strip), and the values are preserved through validation.
48
+ * - Trusted server code that needs to write internals directly — e.g.
49
+ * workflow transitions invoked from an authorized admin route — must use
50
+ * `AdminClient.updateInternal()`, which bypasses the strip.
51
+ *
52
+ * Use this flag on any field added by a behavior whose value represents a
53
+ * controlled state machine (e.g. `_workflowStatus`), not user input.
54
+ */
55
+ internal?: boolean;
39
56
  access?: {
40
57
  view?: string;
41
58
  edit?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/refs/find-usages.ts","../../src/refs/errors.ts","../../src/fields/base.ts","../../src/refs/extract-refs.ts","../../src/refs/schema.ts"],"mappings":";;;;UAUiB,WAAA;E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kB,eAAA;EACjC,IAAA;AAAA;AAAA,UAGe,WAAA,SAAoB,eAAA;EACnC,IAAA;EACA,MAAA,WAAiB,kBAAA;EACjB,GAAA;EACA,GAAA;EACA,SAAA;AAAA;AAAA,KAGU,WAAA,GACR,OAAA,GACA,SAAA,GACA,WAAA,GACA,YAAA,GACA,SAAA,GACA,WAAA,GACA,cAAA,GACA,UAAA,GACA,aAAA,GACA,SAAA,GACA,SAAA,GACA,WAAA;;;UCrGa,YAAA;EACf,WAAA;EACA,YAAA;EACA,QAAA;AAAA;;;;;;;;iBAUc,WAAA,CACd,SAAA,EAAW,MAAA,SAAe,WAAA,GAC1B,IAAA,EAAM,MAAA,oBACL,YAAA;;;;;iBAsFa,mBAAA,CAAoB,SAAA,EAAW,MAAA,SAAe,WAAA;;;;;;;AH1G9D;;;;;cIEa,UAAA,yBAAU,kBAAA;;;;kBAoBtB,sBAAA,CAAA,QAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/refs/find-usages.ts","../../src/refs/errors.ts","../../src/fields/base.ts","../../src/refs/extract-refs.ts","../../src/refs/schema.ts"],"mappings":";;;;UAUiB,WAAA;EACf,YAAA;EACA,QAAA;EACA,WAAA;AAAA;;;AAWF;;;;;;iBAAsB,gBAAA,CACpB,YAAA,UACA,QAAA,UACA,EAAA,EAAI,kBAAA,GACH,OAAA,CAAQ,WAAA;;;cCtBE,qBAAA,SAA8B,KAAA;EAAA,SACzB,UAAA;EAAA,SACA,QAAA;EAAA,SACA,MAAA,EAAQ,WAAA;cAEZ,UAAA,UAAoB,QAAA,UAAkB,MAAA,EAAQ,WAAA;AAAA;;;;;;;UCN3C,eAAA;EACf,QAAA;EACA,OAAA;EACA,YAAA;EACA,OAAA;EACA,MAAA;EFGA;;;AAWF;;;;;;;;;;;;;EEGE,QAAA;EACA,MAAA;IACE,IAAA;IACA,IAAA;EAAA;AAAA;AAAA,UAIa,OAAA,SAAgB,eAAA;EAC/B,IAAA;AAAA;AAAA,UAGe,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W,MAAA,SAAe,WAAA;;;;;;;AH1G9D;;;;;cIEa,UAAA,yBAAU,kBAAA;;;;kBAoBtB,sBAAA,CAAA,QAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/refs/errors.ts","../../src/refs/extract-refs.ts","../../src/refs/schema.ts","../../src/refs/find-usages.ts"],"sourcesContent":["/**\n * Error thrown when attempting to delete an entity that is still referenced.\n */\n\nimport type { EntityUsage } from './find-usages.js'\n\nexport class ReferencedEntityError extends Error {\n public readonly entityName: string\n public readonly entityId: string\n public readonly usages: EntityUsage[]\n\n constructor(entityName: string, entityId: string, usages: EntityUsage[]) {\n const count = usages.length\n super(\n `Cannot delete ${entityName} '${entityId}': referenced by ${count} other entit${count === 1 ? 'y' : 'ies'}`,\n )\n this.name = 'ReferencedEntityError'\n this.entityName = entityName\n this.entityId = entityId\n this.usages = usages\n }\n}\n","/**\n * Schema-aware reference extraction.\n *\n * Walks entity field definitions and data to find all outgoing references.\n * Handles:\n * - field.media() → target = 'media', single UUID\n * - field.reference() → target = config.entity, single UUID or UUID[]\n * - field.blocks() → inspects block instance data for media/reference fields\n */\n\nimport type { BlocksField, FieldConfig, ReferenceField } from '../fields/base.js'\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nexport interface ExtractedRef {\n sourceField: string\n targetEntity: string\n targetId: string\n}\n\n/**\n * Extract all outgoing references from entity data.\n *\n * @param allFields - The entity's complete field map (entity.allFields)\n * @param data - The entity data (full on create, partial on update)\n * @returns Deduplicated array of extracted references\n */\nexport function extractRefs(\n allFields: Record<string, FieldConfig>,\n data: Record<string, unknown>,\n): ExtractedRef[] {\n const refs: ExtractedRef[] = []\n const seen = new Set<string>()\n\n function add(sourceField: string, targetEntity: string, targetId: string) {\n if (!UUID_RE.test(targetId)) return\n const key = `${sourceField}|${targetEntity}|${targetId}`\n if (seen.has(key)) return\n seen.add(key)\n refs.push({ sourceField, targetEntity, targetId })\n }\n\n for (const [fieldName, config] of Object.entries(allFields)) {\n const value = data[fieldName]\n if (value == null) continue\n\n switch (config.type) {\n case 'media': {\n if (typeof value === 'string') {\n add(fieldName, 'media', value)\n }\n break\n }\n\n case 'reference': {\n const refConfig = config as ReferenceField\n if (refConfig.cardinality === 'many' && Array.isArray(value)) {\n for (const id of value) {\n if (typeof id === 'string') {\n add(fieldName, refConfig.entity, id)\n }\n }\n } else if (typeof value === 'string') {\n add(fieldName, refConfig.entity, value)\n }\n break\n }\n\n case 'blocks': {\n const blocksConfig = config as BlocksField\n if (!Array.isArray(value)) break\n\n for (const block of value) {\n const inst = block as Record<string, unknown>\n const blockType = inst._block as string | undefined\n if (!blockType) continue\n\n // Find the block definition to know its field types\n const blockDef = blocksConfig.blocks.find((b) => b.slug === blockType)\n if (!blockDef) continue\n\n // Scan block fields for media/reference values\n for (const [blockFieldName, blockFieldConfig] of Object.entries(blockDef.fields)) {\n const blockValue = inst[blockFieldName]\n if (blockValue == null) continue\n\n if (blockFieldConfig.type === 'media' && typeof blockValue === 'string') {\n add(fieldName, 'media', blockValue)\n }\n\n if (blockFieldConfig.type === 'reference') {\n const blockRefConfig = blockFieldConfig as ReferenceField\n if (blockRefConfig.cardinality === 'many' && Array.isArray(blockValue)) {\n for (const id of blockValue) {\n if (typeof id === 'string') {\n add(fieldName, blockRefConfig.entity, id)\n }\n }\n } else if (typeof blockValue === 'string') {\n add(fieldName, blockRefConfig.entity, blockValue)\n }\n }\n }\n }\n break\n }\n }\n }\n\n return refs\n}\n\n/**\n * Get the names of all ref-bearing fields in the entity.\n * Used to scope partial-update ref deletion.\n */\nexport function getRefBearingFields(allFields: Record<string, FieldConfig>): string[] {\n const names: string[] = []\n for (const [fieldName, config] of Object.entries(allFields)) {\n if (config.type === 'media' || config.type === 'reference' || config.type === 'blocks') {\n names.push(fieldName)\n }\n }\n return names\n}\n","/**\n * entity_refs — Universal reference tracking table.\n *\n * Every reference between entities (field.media(), field.reference(), block media fields)\n * gets a row here at write time. This enables:\n * - Instant \"where is this used?\" queries (one indexed lookup)\n * - Universal delete protection (can't delete referenced entities)\n * - Correct results (schema-aware, no LIKE text search)\n */\n\nimport { index, pgTable, unique, uuid, varchar } from 'drizzle-orm/pg-core'\n\nexport const entityRefs = pgTable(\n 'entity_refs',\n {\n sourceEntity: varchar('source_entity', { length: 100 }).notNull(),\n sourceId: uuid('source_id').notNull(),\n sourceField: varchar('source_field', { length: 100 }).notNull(),\n targetEntity: varchar('target_entity', { length: 100 }).notNull(),\n targetId: uuid('target_id').notNull(),\n },\n (t) => [\n unique('uq_entity_refs').on(\n t.sourceEntity,\n t.sourceId,\n t.sourceField,\n t.targetEntity,\n t.targetId,\n ),\n index('idx_entity_refs_target').on(t.targetEntity, t.targetId),\n index('idx_entity_refs_source').on(t.sourceEntity, t.sourceId),\n ],\n)\n","/**\n * Generic entity usage lookup — \"where is this entity referenced?\"\n *\n * One indexed query on entity_refs instead of scanning every table.\n */\n\nimport { and, eq } from 'drizzle-orm'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport { entityRefs } from './schema.js'\n\nexport interface EntityUsage {\n sourceEntity: string\n sourceId: string\n sourceField: string\n}\n\n/**\n * Find all entities that reference a given entity.\n *\n * @param targetEntity - Entity type name (e.g. 'media', 'category')\n * @param targetId - UUID of the referenced entity\n * @param db - Database connection\n * @returns Array of usage records (empty if unreferenced)\n */\nexport async function findEntityUsages(\n targetEntity: string,\n targetId: string,\n db: PostgresJsDatabase,\n): Promise<EntityUsage[]> {\n const rows = await db\n .select({\n sourceEntity: entityRefs.sourceEntity,\n sourceId: entityRefs.sourceId,\n sourceField: entityRefs.sourceField,\n })\n .from(entityRefs)\n .where(and(eq(entityRefs.targetEntity, targetEntity), eq(entityRefs.targetId, targetId)))\n\n return rows\n}\n"],"mappings":"sIAMA,IAAa,EAAb,cAA2C,KAAM,CAC/C,WACA,SACA,OAEA,YAAY,EAAoB,EAAkB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,EAAI,EAAG,EAAW,aAAc,EAAa,CAAE,EAAG,EAAW,SAAU,EAAS,CAAC,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/refs/errors.ts","../../src/refs/extract-refs.ts","../../src/refs/schema.ts","../../src/refs/find-usages.ts"],"sourcesContent":["/**\n * Error thrown when attempting to delete an entity that is still referenced.\n */\n\nimport type { EntityUsage } from './find-usages.js'\n\nexport class ReferencedEntityError extends Error {\n public readonly entityName: string\n public readonly entityId: string\n public readonly usages: EntityUsage[]\n\n constructor(entityName: string, entityId: string, usages: EntityUsage[]) {\n const count = usages.length\n super(\n `Cannot delete ${entityName} '${entityId}': referenced by ${count} other entit${count === 1 ? 'y' : 'ies'}`,\n )\n this.name = 'ReferencedEntityError'\n this.entityName = entityName\n this.entityId = entityId\n this.usages = usages\n }\n}\n","/**\n * Schema-aware reference extraction.\n *\n * Walks entity field definitions and data to find all outgoing references.\n * Handles:\n * - field.media() → target = 'media', single UUID\n * - field.reference() → target = config.entity, single UUID or UUID[]\n * - field.blocks() → inspects block instance data for media/reference fields\n */\n\nimport type { BlocksField, FieldConfig, ReferenceField } from '../fields/base.js'\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nexport interface ExtractedRef {\n sourceField: string\n targetEntity: string\n targetId: string\n}\n\n/**\n * Extract all outgoing references from entity data.\n *\n * @param allFields - The entity's complete field map (entity.allFields)\n * @param data - The entity data (full on create, partial on update)\n * @returns Deduplicated array of extracted references\n */\nexport function extractRefs(\n allFields: Record<string, FieldConfig>,\n data: Record<string, unknown>,\n): ExtractedRef[] {\n const refs: ExtractedRef[] = []\n const seen = new Set<string>()\n\n function add(sourceField: string, targetEntity: string, targetId: string) {\n if (!UUID_RE.test(targetId)) return\n const key = `${sourceField}|${targetEntity}|${targetId}`\n if (seen.has(key)) return\n seen.add(key)\n refs.push({ sourceField, targetEntity, targetId })\n }\n\n for (const [fieldName, config] of Object.entries(allFields)) {\n const value = data[fieldName]\n if (value == null) continue\n\n switch (config.type) {\n case 'media': {\n if (typeof value === 'string') {\n add(fieldName, 'media', value)\n }\n break\n }\n\n case 'reference': {\n const refConfig = config as ReferenceField\n if (refConfig.cardinality === 'many' && Array.isArray(value)) {\n for (const id of value) {\n if (typeof id === 'string') {\n add(fieldName, refConfig.entity, id)\n }\n }\n } else if (typeof value === 'string') {\n add(fieldName, refConfig.entity, value)\n }\n break\n }\n\n case 'blocks': {\n const blocksConfig = config as BlocksField\n if (!Array.isArray(value)) break\n\n for (const block of value) {\n const inst = block as Record<string, unknown>\n const blockType = inst._block as string | undefined\n if (!blockType) continue\n\n // Find the block definition to know its field types\n const blockDef = blocksConfig.blocks.find((b) => b.slug === blockType)\n if (!blockDef) continue\n\n // Scan block fields for media/reference values\n for (const [blockFieldName, blockFieldConfig] of Object.entries(blockDef.fields)) {\n const blockValue = inst[blockFieldName]\n if (blockValue == null) continue\n\n if (blockFieldConfig.type === 'media' && typeof blockValue === 'string') {\n add(fieldName, 'media', blockValue)\n }\n\n if (blockFieldConfig.type === 'reference') {\n const blockRefConfig = blockFieldConfig as ReferenceField\n if (blockRefConfig.cardinality === 'many' && Array.isArray(blockValue)) {\n for (const id of blockValue) {\n if (typeof id === 'string') {\n add(fieldName, blockRefConfig.entity, id)\n }\n }\n } else if (typeof blockValue === 'string') {\n add(fieldName, blockRefConfig.entity, blockValue)\n }\n }\n }\n }\n break\n }\n }\n }\n\n return refs\n}\n\n/**\n * Get the names of all ref-bearing fields in the entity.\n * Used to scope partial-update ref deletion.\n */\nexport function getRefBearingFields(allFields: Record<string, FieldConfig>): string[] {\n const names: string[] = []\n for (const [fieldName, config] of Object.entries(allFields)) {\n if (config.type === 'media' || config.type === 'reference' || config.type === 'blocks') {\n names.push(fieldName)\n }\n }\n return names\n}\n","/**\n * entity_refs — Universal reference tracking table.\n *\n * Every reference between entities (field.media(), field.reference(), block media fields)\n * gets a row here at write time. This enables:\n * - Instant \"where is this used?\" queries (one indexed lookup)\n * - Universal delete protection (can't delete referenced entities)\n * - Correct results (schema-aware, no LIKE text search)\n */\n\nimport { index, pgTable, unique, uuid, varchar } from 'drizzle-orm/pg-core'\n\nexport const entityRefs = pgTable(\n 'entity_refs',\n {\n sourceEntity: varchar('source_entity', { length: 100 }).notNull(),\n sourceId: uuid('source_id').notNull(),\n sourceField: varchar('source_field', { length: 100 }).notNull(),\n targetEntity: varchar('target_entity', { length: 100 }).notNull(),\n targetId: uuid('target_id').notNull(),\n },\n (t) => [\n unique('uq_entity_refs').on(\n t.sourceEntity,\n t.sourceId,\n t.sourceField,\n t.targetEntity,\n t.targetId,\n ),\n index('idx_entity_refs_target').on(t.targetEntity, t.targetId),\n index('idx_entity_refs_source').on(t.sourceEntity, t.sourceId),\n ],\n)\n","/**\n * Generic entity usage lookup — \"where is this entity referenced?\"\n *\n * One indexed query on entity_refs instead of scanning every table.\n */\n\nimport { and, eq } from 'drizzle-orm'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport { entityRefs } from './schema.js'\n\nexport interface EntityUsage {\n sourceEntity: string\n sourceId: string\n sourceField: string\n}\n\n/**\n * Find all entities that reference a given entity.\n *\n * @param targetEntity - Entity type name (e.g. 'media', 'category')\n * @param targetId - UUID of the referenced entity\n * @param db - Database connection\n * @returns Array of usage records (empty if unreferenced)\n */\nexport async function findEntityUsages(\n targetEntity: string,\n targetId: string,\n db: PostgresJsDatabase,\n): Promise<EntityUsage[]> {\n const rows = await db\n .select({\n sourceEntity: entityRefs.sourceEntity,\n sourceId: entityRefs.sourceId,\n sourceField: entityRefs.sourceField,\n })\n .from(entityRefs)\n .where(and(eq(entityRefs.targetEntity, targetEntity), eq(entityRefs.targetId, targetId)))\n\n return rows\n}\n"],"mappings":"sIAMA,IAAa,EAAb,cAA2C,KAAM,CAC/C,WACA,SACA,OAEA,YAAY,EAAoB,EAAkB,EAAuB,CACvE,IAAM,EAAQ,EAAO,OACrB,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AG,EAAW,SAAU,EAAS,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@murumets-ee/entity",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "license": "Elastic-2.0",
5
5
  "type": "module",
6
6
  "exports": {
@@ -28,10 +28,10 @@
28
28
  "drizzle-orm": "^0.45.2",
29
29
  "zod": "^3.24.1",
30
30
  "server-only": "^0.0.1",
31
- "@murumets-ee/db": "0.10.0"
31
+ "@murumets-ee/db": "0.12.0"
32
32
  },
33
33
  "devDependencies": {
34
- "tsdown": "^0.21.7",
34
+ "tsdown": "^0.21.10",
35
35
  "typescript": "^5.7.2",
36
36
  "vitest": "^2.1.8"
37
37
  },