@murumets-ee/entity 0.1.4 → 0.1.5

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.
@@ -0,0 +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/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;EACjB,UAAA,CAAW,MAAA;AAAA;;;;UCKI,WAAA;;EAEf,KAAA;EAF0B;EAI1B,KAAA;EAJ0B;EAM1B,SAAA;EAFA;EAIA,EAAA;AAAA;;;;;;;UC7Be,iBAAA;EFaA;EEXf,KAAA;;EAEA,KAAA;EFUA;EERA,aAAA;EFSA;EEPA,IAAA;EFOiB;EELjB,WAAA;EFMW;EEJX,MAAA;EFIyB;EEFzB,YAAA;;EAEA,aAAA;EDKe;ECHf,cAAA,GAAiB,MAAA;IAAiB,KAAA;IAAgB,WAAA;IAAsB,WAAA;EAAA;EDSxE;ECPA,WAAA;EDSE;ECPF,oBAAA;;EAEA,QAAA;;EAEA,UAAA;EA1BgC;EA4BhC,aAAA;EAVuB;EAYvB,SAAA;AAAA;;;;;;;UC7Be,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;AAAA;AAAA,UAGe,SAAA,SAAkB,eAAA;EACjC,IAAA;EACA,SAAA;EACA,SAAA;EACA,OAAA,GAAU,MAAA;AAAA;AAAA,UAGK,WAAA,SAAoB,eAAA;EACnC,IAAA;EACA,GAAA;EACA,GAAA;EACA,OAAA;AAAA;AAAA,U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qB;;;EAAA,QKsU3B,eAAA;ELlUR;;;AAGF;;;;;EAHE,QKgVc,UAAA;ELzUW;;;EAAA,QK8cjB,YAAA;EL9cyB;;;;EAAA,QKuezB,kBAAA;AAAA"}
@@ -0,0 +1,7 @@
1
+ import{schemaRegistry as e}from"@murumets-ee/db";import{and as t,eq as n,gt as r,inArray as i,isNull as a,lt as o,or as s,sql as c}from"drizzle-orm";function l(e,i){let a=e[i.field];if(!a)return null;let c=i.direction===`desc`?o:r,l=c(a,i.value);if(!i.id)return l;let u=e.id;if(!u)return l;let d=c(u,i.id);return s(l,t(n(a,i.value),d))}function u(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 d(e,t,n){return t.map(t=>u(e,t,n))}var f=class{entity;db;logger;table;isPublishable;countCache;constructor(t){this.entity=t.entity,this.db=t.db,this.logger=t.logger,this.countCache=t.countCache,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 i=[n(this.table.id,e)];this.isPublishable&&i.push(this.buildPublishFilter(r?.locale));let[a]=await this.db.select().from(this.table).where(t(...i));if(!a)return null;let o=u(this.entity,a,{select:r?.select});if(!o)return null;if(this.getBlocksFields().length>0){let e=await this.loadBlocks([o.id],r?.locale,{defaultLocale:r?.defaultLocale});this.attachBlocks([o],e)}return r?.locale?(await this.mergeTranslations([o],r.locale))[0]:o}async findMany(e){this.logger?.info({entity:this.entity.name,options:e,locale:e?.locale},`Query: Finding entities`);let n=this.db.select().from(this.table).$dynamic(),r=[];if(this.isPublishable&&r.push(this.buildPublishFilter(e?.locale)),e?.where&&r.push(e.where),e?.cursor){let t=this.entity.allFields;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=l(this.table,e.cursor);n&&r.push(n)}if(r.length>0&&(n=n.where(t(...r))),e?.limit&&(n=n.limit(e.limit)),e?.offset&&!e?.cursor&&(n=n.offset(e.offset)),e?.orderBy){let t=Array.isArray(e.orderBy)?e.orderBy:[e.orderBy];n=n.orderBy(...t)}let i=await n,a=d(this.entity,i,{select:e?.select}).filter(e=>e!==null);if(this.getBlocksFields().length>0&&a.length>0){let t=a.map(e=>e.id),n=await this.loadBlocks(t,e?.locale,{defaultLocale:e?.defaultLocale});this.attachBlocks(a,n)}return e?.locale?await this.mergeTranslations(a,e.locale):a}async count(e){this.logger?.info({entity:this.entity.name,options:e},`Query: Counting entities`);let n=this.buildCountCacheKey(e?.where);if(this.countCache){let e=this.countCache.get(n);if(e!==void 0)return this.logger?.debug?.({entity:this.entity.name,cached:e},`Count cache hit`),e}let r=this.db.select({count:c`count(*)`}).from(this.table).$dynamic();if(this.isPublishable){let n=this.buildPublishFilter();r=e?.where?r.where(t(n,e.where)):r.where(n)}else e?.where&&(r=r.where(e.where));let[i]=await r,a=Number(i.count);return this.countCache&&this.countCache.set(n,a),a}buildPublishFilter(t){if(t){let n=e.get(`${this.entity.name}_locale_status`);if(n)return c`COALESCE(
2
+ (SELECT ${n.status} FROM ${n}
3
+ WHERE ${n.entityId} = ${this.table.id}
4
+ AND ${n.locale} = ${t}),
5
+ ${this.table.status}
6
+ ) = 'published'`}return n(this.table.status,`published`)}async mergeTranslations(r,a){if(!r.length)return r;let o=`${this.entity.name}_translations`,s=e.get(o);if(!s)return r;let c=r.map(e=>e.id),l=await this.db.select().from(s).where(t(i(s.entityId,c),n(s.locale,a))),u=Object.entries(this.entity.allFields).filter(([e,t])=>t.translatable).map(([e])=>e),d=new Map;for(let e of l){let t={};for(let n of u){let r=e[n];r!=null&&(t[n]=r)}d.set(e.entityId,t)}return r.map(e=>{let t=d.get(e.id);return t?{...e,...t}:e})}getBlocksFields(){return Object.entries(this.entity.allFields).filter(([e,t])=>t.type===`blocks`).map(([e,t])=>({name:e,config:t}))}async loadBlocks(r,o,c){let l=this.getBlocksFields();if(l.length===0||r.length===0)return new Map;let u=e.get(`${this.entity.name}_layout`);if(!u)return new Map;let d=l.filter(({config:e})=>!(`localized`in e&&e.localized)),f=l.filter(({config:e})=>`localized`in e&&e.localized),p=new Map;if(d.length>0){let s=await this.db.select().from(u).where(t(i(u.entityId,r),a(u.locale))).orderBy(u.sortOrder),c;if(o&&s.length>0){let r=e.get(`${this.entity.name}_layout_translations`);if(r){let e=s.map(e=>e.id),a=await this.db.select().from(r).where(t(i(r.layoutId,e),n(r.locale,o)));c=new Map;for(let e of a)c.set(e.layoutId,e.fields??{})}}for(let e of s){let t=e.entityId,n=e.fieldName;p.has(t)||p.set(t,{});let r=p.get(t);r[n]||(r[n]=[]);let i=e.data??{},a=c?.get(e.id);r[n].push({_block:e.blockType,_id:e.id,...i,...a??{}})}}if(f.length>0){let e=!o||o===c?.defaultLocale,l=o?e?s(n(u.locale,o),a(u.locale)):n(u.locale,o):a(u.locale),d=await this.db.select().from(u).where(t(i(u.entityId,r),l)).orderBy(u.sortOrder),f=new Map;for(let e of d){let t=`${e.entityId}::${e.fieldName}`;f.has(t)||f.set(t,{localeRows:[],nullRows:[]});let n=f.get(t);e.locale?n.localeRows.push(e):n.nullRows.push(e)}for(let[,{localeRows:e,nullRows:t}]of f){let n=e.length>0?e:t;for(let e of n){let t=e.entityId,n=e.fieldName;p.has(t)||p.set(t,{});let r=p.get(t);r[n]||(r[n]=[]);let i=e.data??{};r[n].push({_block:e.blockType,_id:e.id,...i})}}}return p}attachBlocks(e,t){let n=this.getBlocksFields();if(n.length!==0)for(let r of e){let e=r.id,i=t.get(e)??{};for(let{name:e}of n)r[e]=i[e]??[]}}buildCountCacheKey(e){let t=`query:${this.entity.name}`;return e?`${t}:${String(e)}`:t}};export{f as QueryClient};
7
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/cursor.ts","../../src/dto-shaper.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, gt, lt, or, type SQL } from 'drizzle-orm'\nimport type { PgTableWithColumns } 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(\n // biome-ignore lint/suspicious/noExplicitAny: dynamic table columns require PgTableWithColumns<any> for property access\n table: PgTableWithColumns<any>,\n cursor: DecodedCursor,\n): SQL | null {\n const column = table[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 = table.id\n if (!idColumn) return fieldCondition\n\n const idCondition = compare(idColumn, cursor.id)\n return or(fieldCondition, and(eq(column, cursor.value), idCondition))!\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 * 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, inArray, isNull, or, 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 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}\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 * Security:\n * - NO 'server-only' import (safe for client bundles)\n * - Uses read-only DB connection (PostgreSQL enforces with default_transaction_read_only=on)\n * - NO mutation methods on TypeScript type (create/update/delete don't exist)\n * - Auto-filters to published entities if entity has publishable() behavior\n *\n * Phase 1: Core read operations + publishable filtering\n * Phase 2 (TODO): Translation merging, reference population\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\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\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 // Query database\n const whereConditions = [eq(this.table.id, id)]\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 (this.getBlocksFields().length > 0) {\n const blocksMap = await this.loadBlocks([shaped.id as string], options?.locale, {\n defaultLocale: options?.defaultLocale,\n })\n this.attachBlocks([shaped], blocksMap)\n }\n\n // PHASE 3: Merge translations if locale specified\n if (options?.locale) {\n const merged = await this.mergeTranslations([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 // Build query\n let query = this.db.select().from(this.table).$dynamic()\n\n // Collect WHERE conditions\n const conditions: SQL[] = []\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 = this.entity.allFields as Record<string, FieldConfig>\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 (this.getBlocksFields().length > 0 && shaped.length > 0) {\n const entityIds = shaped.map((e) => e.id as string)\n const blocksMap = await this.loadBlocks(entityIds, options?.locale, {\n defaultLocale: options?.defaultLocale,\n })\n this.attachBlocks(shaped, blocksMap)\n }\n\n // PHASE 3: Merge translations if locale specified\n if (options?.locale) {\n return (await this.mergeTranslations(shaped, options.locale)) 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 // Build cache key: entityName + serialized WHERE (or empty for unfiltered)\n const cacheKey = this.buildCountCacheKey(options?.where)\n if (this.countCache) {\n const cached = this.countCache.get(cacheKey)\n if (cached !== undefined) {\n this.logger?.debug?.({ entity: this.entity.name, cached }, 'Count cache hit')\n return cached\n }\n }\n\n // Build count query\n let query = this.db.select({ count: sql<number>`count(*)` }).from(this.table).$dynamic()\n\n // Auto-filter to published if entity has publishable behavior\n if (this.isPublishable) {\n const publishedCondition = this.buildPublishFilter()\n\n if (options?.where) {\n query = query.where(and(publishedCondition, options.where))\n } else {\n query = query.where(publishedCondition)\n }\n } else if (options?.where) {\n query = query.where(options.where)\n }\n\n const [result] = await query\n const count = Number(result.count)\n\n // Cache the result\n if (this.countCache) {\n this.countCache.set(cacheKey, count)\n }\n\n return count\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 /**\n * Merge translations into entities for the specified locale.\n * Reads translatable field values from real columns on the translation row.\n */\n private async mergeTranslations<T extends Record<string, unknown>>(\n entities: T[],\n locale: string,\n ): Promise<T[]> {\n if (!entities.length) return entities\n\n const translationTableName = `${this.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 this.db\n .select()\n .from(translationTable)\n .where(\n and(inArray(translationTable.entityId, entityIds), eq(translationTable.locale, locale)),\n )\n\n // Get translatable field names\n const translatableFields = Object.entries(this.entity.allFields as Record<string, FieldConfig>)\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 (layout table)\n // ---------------------------------------------------------------\n\n /**\n * Get all blocks field names for this entity.\n */\n private getBlocksFields(): Array<{ name: string; config: FieldConfig }> {\n return Object.entries(this.entity.allFields as Record<string, FieldConfig>)\n .filter(([_, config]) => config.type === 'blocks')\n .map(([name, config]) => ({ name, config }))\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 * (keeps base data as fallback for untranslated fields — visitor-facing)\n * - Per-locale layout (localized: true): loads rows matching the provided locale only\n */\n private async loadBlocks(\n entityIds: string[],\n locale?: string,\n options?: { defaultLocale?: string },\n ): Promise<Map<string, Record<string, unknown[]>>> {\n const blocksFields = this.getBlocksFields()\n if (blocksFields.length === 0 || entityIds.length === 0) {\n return new Map()\n }\n\n const layoutTable = schemaRegistry.get(`${this.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 this.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 (fallback: base data preserved)\n let blockTransMap: Map<string, Record<string, unknown>> | undefined\n if (locale && rows.length > 0) {\n const layoutTransTable = schemaRegistry.get(`${this.entity.name}_layout_translations`)\n if (layoutTransTable) {\n const layoutIds = rows.map((r) => r.id as string)\n const translations = await this.db\n .select()\n .from(layoutTransTable)\n .where(\n and(\n inArray(layoutTransTable.layoutId, layoutIds),\n eq(layoutTransTable.locale, locale),\n ),\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 for (const row of rows) {\n const eid = row.entityId as string\n const fname = row.fieldName as string\n\n if (!result.has(eid)) result.set(eid, {})\n const entityBlocks = result.get(eid)!\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 // Merge translations on top of base data (fallback: base data for untranslated)\n entityBlocks[fname].push({\n _block: row.blockType,\n _id: row.id,\n ...blockData,\n ...(translatedFields ?? {}),\n })\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 const localeCondition = locale\n ? isDefault\n ? or(eq(layoutTable.locale, locale), isNull(layoutTable.locale))!\n : eq(layoutTable.locale, locale)\n : isNull(layoutTable.locale)\n\n const rows = await this.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 if (!grouped.has(key)) grouped.set(key, { localeRows: [], nullRows: [] })\n const group = grouped.get(key)!\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 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 if (!result.has(eid)) result.set(eid, {})\n const entityBlocks = result.get(eid)!\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 */\n private attachBlocks(\n entities: Record<string, unknown>[],\n blocksMap: Map<string, Record<string, unknown[]>>,\n ): void {\n const blocksFields = this.getBlocksFields()\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 helpers\n // ---------------------------------------------------------------\n\n /**\n * Build a cache key for a count query.\n * Includes the publishable filter implicitly (all QueryClient counts include it).\n */\n private buildCountCacheKey(where?: SQL): string {\n const base = `query:${this.entity.name}`\n if (!where) return base\n return `${base}:${String(where)}`\n }\n\n // NO create/update/delete methods\n // These physically don't exist on the TypeScript type - security by design\n}\n"],"mappings":"qJAwIA,SAAgB,EAEd,EACA,EACY,CACZ,IAAM,EAAS,EAAM,EAAO,OAC5B,GAAI,CAAC,EAAQ,OAAO,KAGpB,IAAM,EADS,EAAO,YAAc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AAS,CAClD,IAAM,EAAY,EAAW,OAAS,EAAI,EAAa,EAEvD,IAAK,IAAM,KAAO,EAAW,CAC3B,IAAM,EAAM,EAAI,SACV,EAAQ,EAAI,UAEb,EAAO,IAAI,EAAI,EAAE,EAAO,IAAI,EAAK,EAAE,CAAC,CACzC,IAAM,EAAe,EAAO,IAAI,EAAI,CAC/B,EAAa,KAAQ,EAAa,GAAS,EAAE,EAElD,IAAM,EAAa,EAAI,MAAoC,EAAE,CAE7D,EAAa,GAAO,KAAK,CACvB,OAAQ,EAAI,UACZ,IAAK,EAAI,GACT,GAAG,EACJ,CAAC,GAKR,OAAO,EAMT,aACE,EACA,EACM,CACN,IAAM,EAAe,KAAK,iBAAiB,CACvC,KAAa,SAAW,EAE5B,IAAK,IAAM,KAAU,EAAU,CAC7B,IAAM,EAAM,EAAO,GACb,EAAe,EAAU,IAAI,EAAI,EAAI,EAAE,CAE7C,IAAK,GAAM,CAAE,UAAU,EACrB,EAAO,GAAQ,EAAa,IAAS,EAAE,EAa7C,mBAA2B,EAAqB,CAC9C,IAAM,EAAO,SAAS,KAAK,OAAO,OAElC,OADK,EACE,GAAG,EAAK,GAAG,OAAO,EAAM,GADZ"}
@@ -0,0 +1,249 @@
1
+ import * as _$drizzle_orm_pg_core0 from "drizzle-orm/pg-core";
2
+ import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
3
+
4
+ //#region src/refs/find-usages.d.ts
5
+ interface EntityUsage {
6
+ sourceEntity: string;
7
+ sourceId: string;
8
+ sourceField: string;
9
+ }
10
+ /**
11
+ * Find all entities that reference a given entity.
12
+ *
13
+ * @param targetEntity - Entity type name (e.g. 'media', 'category')
14
+ * @param targetId - UUID of the referenced entity
15
+ * @param db - Database connection
16
+ * @returns Array of usage records (empty if unreferenced)
17
+ */
18
+ declare function findEntityUsages(targetEntity: string, targetId: string, db: PostgresJsDatabase): Promise<EntityUsage[]>;
19
+ //#endregion
20
+ //#region src/refs/errors.d.ts
21
+ declare class ReferencedEntityError extends Error {
22
+ readonly entityName: string;
23
+ readonly entityId: string;
24
+ readonly usages: EntityUsage[];
25
+ constructor(entityName: string, entityId: string, usages: EntityUsage[]);
26
+ }
27
+ //#endregion
28
+ //#region src/fields/base.d.ts
29
+ /**
30
+ * Field type definitions
31
+ * These define the structure and configuration for all field types
32
+ */
33
+ interface BaseFieldConfig {
34
+ required?: boolean;
35
+ default?: unknown;
36
+ translatable?: boolean;
37
+ indexed?: boolean;
38
+ unique?: boolean;
39
+ access?: {
40
+ view?: string;
41
+ edit?: string;
42
+ };
43
+ }
44
+ interface IdField extends BaseFieldConfig {
45
+ type: 'id';
46
+ }
47
+ interface TextField extends BaseFieldConfig {
48
+ type: 'text';
49
+ maxLength?: number;
50
+ minLength?: number;
51
+ pattern?: RegExp;
52
+ }
53
+ interface NumberField extends BaseFieldConfig {
54
+ type: 'number';
55
+ min?: number;
56
+ max?: number;
57
+ integer?: boolean;
58
+ }
59
+ interface BooleanField extends BaseFieldConfig {
60
+ type: 'boolean';
61
+ }
62
+ interface DateField extends BaseFieldConfig {
63
+ type: 'date';
64
+ minDate?: Date;
65
+ maxDate?: Date;
66
+ }
67
+ interface SelectField extends BaseFieldConfig {
68
+ type: 'select';
69
+ options: readonly string[];
70
+ }
71
+ interface ReferenceField extends BaseFieldConfig {
72
+ type: 'reference';
73
+ entity: string;
74
+ cardinality: 'one' | 'many';
75
+ onDelete?: 'cascade' | 'set-null' | 'restrict';
76
+ }
77
+ interface MediaField extends BaseFieldConfig {
78
+ type: 'media';
79
+ accept?: string[];
80
+ maxSize?: number;
81
+ }
82
+ interface RichTextField extends BaseFieldConfig {
83
+ type: 'richtext';
84
+ blocks?: string[];
85
+ }
86
+ interface SlugField extends BaseFieldConfig {
87
+ type: 'slug';
88
+ from: string;
89
+ unique?: boolean;
90
+ }
91
+ /**
92
+ * Minimal block definition reference — used by BlocksField to type-check allowed blocks.
93
+ * The full BlockDefinition (with label, etc.) lives in @murumets-ee/content.
94
+ */
95
+ interface BlockDefinitionRef {
96
+ slug: string;
97
+ fields: Record<string, FieldConfig>;
98
+ }
99
+ /**
100
+ * Blocks field — ordered array of typed content blocks.
101
+ * Each block instance stores its data in {entity}_layout table.
102
+ *
103
+ * @property blocks - Allowed block definitions
104
+ * @property min/max - Block count constraints
105
+ * @property localized - true = per-locale layouts, false = shared layout with translated content (default)
106
+ */
107
+ interface JsonField extends BaseFieldConfig {
108
+ type: 'json';
109
+ }
110
+ interface BlocksField extends BaseFieldConfig {
111
+ type: 'blocks';
112
+ blocks: readonly BlockDefinitionRef[];
113
+ min?: number;
114
+ max?: number;
115
+ localized?: boolean;
116
+ }
117
+ type FieldConfig = IdField | TextField | NumberField | BooleanField | DateField | SelectField | ReferenceField | MediaField | RichTextField | SlugField | JsonField | BlocksField;
118
+ //#endregion
119
+ //#region src/refs/extract-refs.d.ts
120
+ interface ExtractedRef {
121
+ sourceField: string;
122
+ targetEntity: string;
123
+ targetId: string;
124
+ }
125
+ /**
126
+ * Extract all outgoing references from entity data.
127
+ *
128
+ * @param allFields - The entity's complete field map (entity.allFields)
129
+ * @param data - The entity data (full on create, partial on update)
130
+ * @returns Deduplicated array of extracted references
131
+ */
132
+ declare function extractRefs(allFields: Record<string, FieldConfig>, data: Record<string, unknown>): ExtractedRef[];
133
+ /**
134
+ * Get the names of all ref-bearing fields in the entity.
135
+ * Used to scope partial-update ref deletion.
136
+ */
137
+ declare function getRefBearingFields(allFields: Record<string, FieldConfig>): string[];
138
+ //#endregion
139
+ //#region src/refs/schema.d.ts
140
+ /**
141
+ * entity_refs — Universal reference tracking table.
142
+ *
143
+ * Every reference between entities (field.media(), field.reference(), block media fields)
144
+ * gets a row here at write time. This enables:
145
+ * - Instant "where is this used?" queries (one indexed lookup)
146
+ * - Universal delete protection (can't delete referenced entities)
147
+ * - Correct results (schema-aware, no LIKE text search)
148
+ */
149
+ declare const entityRefs: _$drizzle_orm_pg_core0.PgTableWithColumns<{
150
+ name: "entity_refs";
151
+ schema: undefined;
152
+ columns: {
153
+ sourceEntity: _$drizzle_orm_pg_core0.PgColumn<{
154
+ name: "source_entity";
155
+ tableName: "entity_refs";
156
+ dataType: "string";
157
+ columnType: "PgVarchar";
158
+ data: string;
159
+ driverParam: string;
160
+ notNull: true;
161
+ hasDefault: false;
162
+ isPrimaryKey: false;
163
+ isAutoincrement: false;
164
+ hasRuntimeDefault: false;
165
+ enumValues: [string, ...string[]];
166
+ baseColumn: never;
167
+ identity: undefined;
168
+ generated: undefined;
169
+ }, {}, {
170
+ length: 100;
171
+ }>;
172
+ sourceId: _$drizzle_orm_pg_core0.PgColumn<{
173
+ name: "source_id";
174
+ tableName: "entity_refs";
175
+ dataType: "string";
176
+ columnType: "PgUUID";
177
+ data: string;
178
+ driverParam: string;
179
+ notNull: true;
180
+ hasDefault: false;
181
+ isPrimaryKey: false;
182
+ isAutoincrement: false;
183
+ hasRuntimeDefault: false;
184
+ enumValues: undefined;
185
+ baseColumn: never;
186
+ identity: undefined;
187
+ generated: undefined;
188
+ }, {}, {}>;
189
+ sourceField: _$drizzle_orm_pg_core0.PgColumn<{
190
+ name: "source_field";
191
+ tableName: "entity_refs";
192
+ dataType: "string";
193
+ columnType: "PgVarchar";
194
+ data: string;
195
+ driverParam: string;
196
+ notNull: true;
197
+ hasDefault: false;
198
+ isPrimaryKey: false;
199
+ isAutoincrement: false;
200
+ hasRuntimeDefault: false;
201
+ enumValues: [string, ...string[]];
202
+ baseColumn: never;
203
+ identity: undefined;
204
+ generated: undefined;
205
+ }, {}, {
206
+ length: 100;
207
+ }>;
208
+ targetEntity: _$drizzle_orm_pg_core0.PgColumn<{
209
+ name: "target_entity";
210
+ tableName: "entity_refs";
211
+ dataType: "string";
212
+ columnType: "PgVarchar";
213
+ data: string;
214
+ driverParam: string;
215
+ notNull: true;
216
+ hasDefault: false;
217
+ isPrimaryKey: false;
218
+ isAutoincrement: false;
219
+ hasRuntimeDefault: false;
220
+ enumValues: [string, ...string[]];
221
+ baseColumn: never;
222
+ identity: undefined;
223
+ generated: undefined;
224
+ }, {}, {
225
+ length: 100;
226
+ }>;
227
+ targetId: _$drizzle_orm_pg_core0.PgColumn<{
228
+ name: "target_id";
229
+ tableName: "entity_refs";
230
+ dataType: "string";
231
+ columnType: "PgUUID";
232
+ data: string;
233
+ driverParam: string;
234
+ notNull: true;
235
+ hasDefault: false;
236
+ isPrimaryKey: false;
237
+ isAutoincrement: false;
238
+ hasRuntimeDefault: false;
239
+ enumValues: undefined;
240
+ baseColumn: never;
241
+ identity: undefined;
242
+ generated: undefined;
243
+ }, {}, {}>;
244
+ };
245
+ dialect: "pg";
246
+ }>;
247
+ //#endregion
248
+ export { type EntityUsage, type ExtractedRef, ReferencedEntityError, entityRefs, extractRefs, findEntityUsages, getRefBearingFields };
249
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +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;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;EACA,MAAA;IACE,IAAA;IACA,IAAA;EAAA;AAAA;AAAA,UAIa,OAAA,SAAgB,eAAA;EAC/B,IAAA;AAAA;AAAA,UAGe,SAAA,SAAkB,eAAA;EACjC,IAAA;EACA,SAAA;EACA,SAAA;EACA,OAAA,GAAU,MAAA;AAAA;AAAA,UAGK,WAAA,SAAoB,e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1,2 @@
1
+ import{and as e,eq as t}from"drizzle-orm";import{index as n,pgTable as r,unique as i,uuid as a,varchar as o}from"drizzle-orm/pg-core";var s=class extends Error{entityName;entityId;usages;constructor(e,t,n){let r=n.length;super(`Cannot delete ${e} '${t}': referenced by ${r} other entit${r===1?`y`:`ies`}`),this.name=`ReferencedEntityError`,this.entityName=e,this.entityId=t,this.usages=n}};const c=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function l(e,t){let n=[],r=new Set;function i(e,t,i){if(!c.test(i))return;let a=`${e}|${t}|${i}`;r.has(a)||(r.add(a),n.push({sourceField:e,targetEntity:t,targetId:i}))}for(let[n,r]of Object.entries(e)){let e=t[n];if(e!=null)switch(r.type){case`media`:typeof e==`string`&&i(n,`media`,e);break;case`reference`:{let t=r;if(t.cardinality===`many`&&Array.isArray(e))for(let r of e)typeof r==`string`&&i(n,t.entity,r);else typeof e==`string`&&i(n,t.entity,e);break}case`blocks`:{let t=r;if(!Array.isArray(e))break;for(let r of e){let e=r,a=e._block;if(!a)continue;let o=t.blocks.find(e=>e.slug===a);if(o)for(let[t,r]of Object.entries(o.fields)){let a=e[t];if(a!=null&&(r.type===`media`&&typeof a==`string`&&i(n,`media`,a),r.type===`reference`)){let e=r;if(e.cardinality===`many`&&Array.isArray(a))for(let t of a)typeof t==`string`&&i(n,e.entity,t);else typeof a==`string`&&i(n,e.entity,a)}}}break}}}return n}function u(e){let t=[];for(let[n,r]of Object.entries(e))(r.type===`media`||r.type===`reference`||r.type===`blocks`)&&t.push(n);return t}const d=r(`entity_refs`,{sourceEntity:o(`source_entity`,{length:100}).notNull(),sourceId:a(`source_id`).notNull(),sourceField:o(`source_field`,{length:100}).notNull(),targetEntity:o(`target_entity`,{length:100}).notNull(),targetId:a(`target_id`).notNull()},e=>[i(`uq_entity_refs`).on(e.sourceEntity,e.sourceId,e.sourceField,e.targetEntity,e.targetId),n(`idx_entity_refs_target`).on(e.targetEntity,e.targetId),n(`idx_entity_refs_source`).on(e.sourceEntity,e.sourceId)]);async function f(n,r,i){return await i.select({sourceEntity:d.sourceEntity,sourceId:d.sourceId,sourceField:d.sourceField}).from(d).where(e(t(d.targetEntity,n),t(d.targetId,r)))}export{s as ReferencedEntityError,d as entityRefs,l as extractRefs,f as findEntityUsages,u as getRefBearingFields};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +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(entityRef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CRD,eAAsB,EACpB,EACA,EACA,EACwB,CAUxB,OATa,MAAM,EAChB,OAAO,CACN,aAAc,EAAW,aACzB,SAAU,EAAW,SACrB,YAAa,EAAW,YACzB,CAAC,CACD,KAAK,EAAW,CAChB,MAAM,EAAI,EAAG,EAAW,aAAc,EAAa,CAAE,EAAG,EAAW,SAAU,EAAS,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,24 +1,24 @@
1
1
  {
2
2
  "name": "@murumets-ee/entity",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "license": "Elastic-2.0",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": {
8
- "types": "./dist/index.d.ts",
9
- "import": "./dist/index.js"
8
+ "types": "./dist/index.d.mts",
9
+ "import": "./dist/index.mjs"
10
10
  },
11
11
  "./admin": {
12
- "types": "./dist/admin/index.d.ts",
13
- "import": "./dist/admin/index.js"
12
+ "types": "./dist/admin/index.d.mts",
13
+ "import": "./dist/admin/index.mjs"
14
14
  },
15
15
  "./query": {
16
- "types": "./dist/query/index.d.ts",
17
- "import": "./dist/query/index.js"
16
+ "types": "./dist/query/index.d.mts",
17
+ "import": "./dist/query/index.mjs"
18
18
  },
19
19
  "./refs": {
20
- "types": "./dist/refs/index.d.ts",
21
- "import": "./dist/refs/index.js"
20
+ "types": "./dist/refs/index.d.mts",
21
+ "import": "./dist/refs/index.mjs"
22
22
  }
23
23
  },
24
24
  "files": [
@@ -28,16 +28,16 @@
28
28
  "drizzle-orm": "^0.45.1",
29
29
  "zod": "^3.24.1",
30
30
  "server-only": "^0.0.1",
31
- "@murumets-ee/db": "0.1.4"
31
+ "@murumets-ee/db": "0.1.5"
32
32
  },
33
33
  "devDependencies": {
34
- "tsup": "^8.3.5",
34
+ "tsdown": "^0.21.7",
35
35
  "typescript": "^5.7.2",
36
36
  "vitest": "^2.1.8"
37
37
  },
38
38
  "scripts": {
39
- "build": "tsup",
40
- "dev": "tsup --watch",
39
+ "build": "tsdown",
40
+ "dev": "tsdown --watch",
41
41
  "test": "vitest",
42
42
  "test:integration": "vitest run --config vitest.integration.config.ts"
43
43
  }