@murumets-ee/content 0.1.1 → 0.1.3

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.
@@ -27,7 +27,7 @@ declare class ContentQueryClient {
27
27
  findById(id: string, options?: FindByIdOptions): Promise<({
28
28
  id: string;
29
29
  } & {} & {
30
- [x: string]: string | number | boolean | Date | Record<string, unknown> | Record<string, unknown>[] | {
30
+ [x: string]: string | number | boolean | Record<string, unknown> | Date | Record<string, unknown>[] | {
31
31
  [key: string]: unknown;
32
32
  _block: string;
33
33
  _id: string;
@@ -41,7 +41,7 @@ declare class ContentQueryClient {
41
41
  }): Promise<({
42
42
  id: string;
43
43
  } & {} & {
44
- [x: string]: string | number | boolean | Date | Record<string, unknown> | Record<string, unknown>[] | {
44
+ [x: string]: string | number | boolean | Record<string, unknown> | Date | Record<string, unknown>[] | {
45
45
  [key: string]: unknown;
46
46
  _block: string;
47
47
  _id: string;
@@ -50,7 +50,7 @@ declare class ContentQueryClient {
50
50
  findMany(options?: FindManyOptions): Promise<({
51
51
  id: string;
52
52
  } & {} & {
53
- [x: string]: string | number | boolean | Date | Record<string, unknown> | Record<string, unknown>[] | {
53
+ [x: string]: string | number | boolean | Record<string, unknown> | Date | Record<string, unknown>[] | {
54
54
  [key: string]: unknown;
55
55
  _block: string;
56
56
  _id: string;
package/package.json CHANGED
@@ -1,38 +1,32 @@
1
1
  {
2
2
  "name": "@murumets-ee/content",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "license": "Elastic-2.0",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": {
8
8
  "types": "./dist/index.d.ts",
9
- "import": "./dist/index.js",
10
- "require": "./dist/index.cjs"
9
+ "import": "./dist/index.js"
11
10
  },
12
11
  "./client": {
13
12
  "types": "./dist/client.d.ts",
14
- "import": "./dist/client.js",
15
- "require": "./dist/client.cjs"
13
+ "import": "./dist/client.js"
16
14
  },
17
15
  "./query": {
18
16
  "types": "./dist/query-client.d.ts",
19
- "import": "./dist/query-client.js",
20
- "require": "./dist/query-client.cjs"
17
+ "import": "./dist/query-client.js"
21
18
  },
22
19
  "./plugin": {
23
20
  "types": "./dist/plugin.d.ts",
24
- "import": "./dist/plugin.js",
25
- "require": "./dist/plugin.cjs"
21
+ "import": "./dist/plugin.js"
26
22
  },
27
23
  "./blocks": {
28
24
  "types": "./dist/blocks/index.d.ts",
29
- "import": "./dist/blocks/index.js",
30
- "require": "./dist/blocks/index.cjs"
25
+ "import": "./dist/blocks/index.js"
31
26
  },
32
27
  "./lock": {
33
28
  "types": "./dist/lock-service.d.ts",
34
- "import": "./dist/lock-service.js",
35
- "require": "./dist/lock-service.cjs"
29
+ "import": "./dist/lock-service.js"
36
30
  }
37
31
  },
38
32
  "files": [
@@ -42,10 +36,10 @@
42
36
  "drizzle-orm": "^0.45.1",
43
37
  "server-only": "^0.0.1",
44
38
  "zod": "^3.24.1",
45
- "@murumets-ee/core": "0.1.1",
46
- "@murumets-ee/logging": "0.1.1",
47
- "@murumets-ee/entity": "0.1.1",
48
- "@murumets-ee/db": "0.1.1"
39
+ "@murumets-ee/core": "0.1.4",
40
+ "@murumets-ee/db": "0.1.3",
41
+ "@murumets-ee/entity": "0.1.3",
42
+ "@murumets-ee/logging": "0.1.4"
49
43
  },
50
44
  "devDependencies": {
51
45
  "@types/node": "^22.10.5",
@@ -1 +0,0 @@
1
- "use strict";var x=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var F=(e,o)=>{for(var a in o)x(e,a,{get:o[a],enumerable:!0})},R=(e,o,a,y)=>{if(o&&typeof o=="object"||typeof o=="function")for(let r of w(o))!T.call(e,r)&&r!==a&&x(e,r,{get:()=>o[r],enumerable:!(y=C(o,r))||y.enumerable});return e};var j=e=>R(x({},"__esModule",{value:!0}),e);var G={};F(G,{CTABlock:()=>s,CodeBlock:()=>c,GalleryBlock:()=>m,HeroBlock:()=>u,ImageBlock:()=>p,QuoteBlock:()=>n,RichTextBlock:()=>d,VideoBlock:()=>k,commonBlocks:()=>A});module.exports=j(G);var B=require("@murumets-ee/entity");function t(e){if(!e.slug||!e.slug.match(/^[a-z][a-z0-9-]*$/))throw new Error(`Block slug must be lowercase alphanumeric with hyphens, got: "${e.slug}"`);if(!e.label)throw new Error(`Block label is required for slug: "${e.slug}"`);if(!e.fields||Object.keys(e.fields).length===0)throw new Error(`Block "${e.slug}" must have at least one field`);return{slug:e.slug,label:e.label,fields:e.fields}}var c=t({slug:"code",label:"Code",fields:{code:B.field.text({required:!0}),language:B.field.select({options:["javascript","typescript","python","html","css","json","bash","sql","other"]})}});var l=require("@murumets-ee/entity");var s=t({slug:"cta",label:"Call to Action",fields:{heading:l.field.text({required:!0,translatable:!0}),description:l.field.text({translatable:!0}),buttonText:l.field.text({required:!0,translatable:!0}),buttonLink:l.field.text({required:!0})}});var b=require("@murumets-ee/entity");var m=t({slug:"gallery",label:"Gallery",fields:{images:b.field.reference({entity:"media",cardinality:"many"}),columns:b.field.select({options:["2","3","4"]})}});var i=require("@murumets-ee/entity");var u=t({slug:"hero",label:"Hero Section",fields:{heading:i.field.text({required:!0,translatable:!0}),subheading:i.field.text({translatable:!0}),background:i.field.media({accept:["image/*"]}),alignment:i.field.select({options:["left","center","right"]})}});var f=require("@murumets-ee/entity");var p=t({slug:"image",label:"Image",fields:{image:f.field.media({accept:["image/*"],required:!0}),alt:f.field.text({translatable:!0}),caption:f.field.text({translatable:!0})}});var h=require("@murumets-ee/entity");var n=t({slug:"quote",label:"Quote",fields:{quote:h.field.text({required:!0,translatable:!0}),attribution:h.field.text({translatable:!0})}});var q=require("@murumets-ee/entity");var d=t({slug:"richtext",label:"Rich Text",fields:{content:q.field.richtext({translatable:!0})}});var g=require("@murumets-ee/entity");var k=t({slug:"video",label:"Video",fields:{url:g.field.text({required:!0}),poster:g.field.media({accept:["image/*"]}),caption:g.field.text({translatable:!0})}});var A=[d,p,u,m,s,k,n,c];0&&(module.exports={CTABlock,CodeBlock,GalleryBlock,HeroBlock,ImageBlock,QuoteBlock,RichTextBlock,VideoBlock,commonBlocks});
@@ -1,187 +0,0 @@
1
- import { B as BlockDefinition } from '../types-BYeiE1ie.cjs';
2
- import * as _murumets_ee_entity from '@murumets-ee/entity';
3
-
4
- declare const CodeBlock: BlockDefinition<{
5
- readonly code: _murumets_ee_entity.TextField & {
6
- readonly required: true;
7
- };
8
- readonly language: _murumets_ee_entity.SelectField & {
9
- options: readonly ["javascript", "typescript", "python", "html", "css", "json", "bash", "sql", "other"];
10
- } & Omit<Partial<_murumets_ee_entity.SelectField>, "options">;
11
- }>;
12
-
13
- declare const CTABlock: BlockDefinition<{
14
- readonly heading: _murumets_ee_entity.TextField & {
15
- readonly required: true;
16
- readonly translatable: true;
17
- };
18
- readonly description: _murumets_ee_entity.TextField & {
19
- readonly translatable: true;
20
- };
21
- readonly buttonText: _murumets_ee_entity.TextField & {
22
- readonly required: true;
23
- readonly translatable: true;
24
- };
25
- readonly buttonLink: _murumets_ee_entity.TextField & {
26
- readonly required: true;
27
- };
28
- }>;
29
-
30
- declare const GalleryBlock: BlockDefinition<{
31
- readonly images: _murumets_ee_entity.ReferenceField & {
32
- cardinality: "many";
33
- } & Partial<Omit<_murumets_ee_entity.ReferenceField, "entity" | "cardinality">>;
34
- readonly columns: _murumets_ee_entity.SelectField & {
35
- options: readonly ["2", "3", "4"];
36
- } & Omit<Partial<_murumets_ee_entity.SelectField>, "options">;
37
- }>;
38
-
39
- declare const HeroBlock: BlockDefinition<{
40
- readonly heading: _murumets_ee_entity.TextField & {
41
- readonly required: true;
42
- readonly translatable: true;
43
- };
44
- readonly subheading: _murumets_ee_entity.TextField & {
45
- readonly translatable: true;
46
- };
47
- readonly background: _murumets_ee_entity.MediaField & {
48
- readonly accept: ["image/*"];
49
- };
50
- readonly alignment: _murumets_ee_entity.SelectField & {
51
- options: readonly ["left", "center", "right"];
52
- } & Omit<Partial<_murumets_ee_entity.SelectField>, "options">;
53
- }>;
54
-
55
- declare const ImageBlock: BlockDefinition<{
56
- readonly image: _murumets_ee_entity.MediaField & {
57
- readonly accept: ["image/*"];
58
- readonly required: true;
59
- };
60
- readonly alt: _murumets_ee_entity.TextField & {
61
- readonly translatable: true;
62
- };
63
- readonly caption: _murumets_ee_entity.TextField & {
64
- readonly translatable: true;
65
- };
66
- }>;
67
-
68
- declare const QuoteBlock: BlockDefinition<{
69
- readonly quote: _murumets_ee_entity.TextField & {
70
- readonly required: true;
71
- readonly translatable: true;
72
- };
73
- readonly attribution: _murumets_ee_entity.TextField & {
74
- readonly translatable: true;
75
- };
76
- }>;
77
-
78
- declare const RichTextBlock: BlockDefinition<{
79
- readonly content: _murumets_ee_entity.RichTextField & {
80
- readonly translatable: true;
81
- };
82
- }>;
83
-
84
- declare const VideoBlock: BlockDefinition<{
85
- readonly url: _murumets_ee_entity.TextField & {
86
- readonly required: true;
87
- };
88
- readonly poster: _murumets_ee_entity.MediaField & {
89
- readonly accept: ["image/*"];
90
- };
91
- readonly caption: _murumets_ee_entity.TextField & {
92
- readonly translatable: true;
93
- };
94
- }>;
95
-
96
- /**
97
- * All common blocks shipped with the toolkit.
98
- * Use as-is or pick individual blocks from the named exports.
99
- *
100
- * @example
101
- * import { commonBlocks } from '@murumets-ee/content/blocks'
102
- * const Page = defineEntity({
103
- * name: 'page',
104
- * fields: {
105
- * layout: field.blocks({ blocks: [...commonBlocks] }),
106
- * },
107
- * })
108
- */
109
- declare const commonBlocks: readonly [BlockDefinition<{
110
- readonly content: _murumets_ee_entity.RichTextField & {
111
- readonly translatable: true;
112
- };
113
- }>, BlockDefinition<{
114
- readonly image: _murumets_ee_entity.MediaField & {
115
- readonly accept: ["image/*"];
116
- readonly required: true;
117
- };
118
- readonly alt: _murumets_ee_entity.TextField & {
119
- readonly translatable: true;
120
- };
121
- readonly caption: _murumets_ee_entity.TextField & {
122
- readonly translatable: true;
123
- };
124
- }>, BlockDefinition<{
125
- readonly heading: _murumets_ee_entity.TextField & {
126
- readonly required: true;
127
- readonly translatable: true;
128
- };
129
- readonly subheading: _murumets_ee_entity.TextField & {
130
- readonly translatable: true;
131
- };
132
- readonly background: _murumets_ee_entity.MediaField & {
133
- readonly accept: ["image/*"];
134
- };
135
- readonly alignment: _murumets_ee_entity.SelectField & {
136
- options: readonly ["left", "center", "right"];
137
- } & Omit<Partial<_murumets_ee_entity.SelectField>, "options">;
138
- }>, BlockDefinition<{
139
- readonly images: _murumets_ee_entity.ReferenceField & {
140
- cardinality: "many";
141
- } & Partial<Omit<_murumets_ee_entity.ReferenceField, "entity" | "cardinality">>;
142
- readonly columns: _murumets_ee_entity.SelectField & {
143
- options: readonly ["2", "3", "4"];
144
- } & Omit<Partial<_murumets_ee_entity.SelectField>, "options">;
145
- }>, BlockDefinition<{
146
- readonly heading: _murumets_ee_entity.TextField & {
147
- readonly required: true;
148
- readonly translatable: true;
149
- };
150
- readonly description: _murumets_ee_entity.TextField & {
151
- readonly translatable: true;
152
- };
153
- readonly buttonText: _murumets_ee_entity.TextField & {
154
- readonly required: true;
155
- readonly translatable: true;
156
- };
157
- readonly buttonLink: _murumets_ee_entity.TextField & {
158
- readonly required: true;
159
- };
160
- }>, BlockDefinition<{
161
- readonly url: _murumets_ee_entity.TextField & {
162
- readonly required: true;
163
- };
164
- readonly poster: _murumets_ee_entity.MediaField & {
165
- readonly accept: ["image/*"];
166
- };
167
- readonly caption: _murumets_ee_entity.TextField & {
168
- readonly translatable: true;
169
- };
170
- }>, BlockDefinition<{
171
- readonly quote: _murumets_ee_entity.TextField & {
172
- readonly required: true;
173
- readonly translatable: true;
174
- };
175
- readonly attribution: _murumets_ee_entity.TextField & {
176
- readonly translatable: true;
177
- };
178
- }>, BlockDefinition<{
179
- readonly code: _murumets_ee_entity.TextField & {
180
- readonly required: true;
181
- };
182
- readonly language: _murumets_ee_entity.SelectField & {
183
- options: readonly ["javascript", "typescript", "python", "html", "css", "json", "bash", "sql", "other"];
184
- } & Omit<Partial<_murumets_ee_entity.SelectField>, "options">;
185
- }>];
186
-
187
- export { CTABlock, CodeBlock, GalleryBlock, HeroBlock, ImageBlock, QuoteBlock, RichTextBlock, VideoBlock, commonBlocks };
package/dist/client.cjs DELETED
@@ -1 +0,0 @@
1
- "use strict";var tt=Object.create;var N=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,st=Object.prototype.hasOwnProperty;var E=(r,e)=>()=>(r&&(e=r(r=0)),e);var D=(r,e)=>{for(var t in e)N(r,t,{get:e[t],enumerable:!0})},P=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nt(e))!st.call(r,i)&&i!==t&&N(r,i,{get:()=>e[i],enumerable:!(n=et(e,i))||n.enumerable});return r};var g=(r,e,t)=>(t=r!=null?tt(it(r)):{},P(e||!r||!r.__esModule?N(t,"default",{value:r,enumerable:!0}):t,r)),rt=r=>P(N({},"__esModule",{value:!0}),r);var K={};D(K,{generateVersionsSchema:()=>dt});function dt(r){let e=`${r.name}_versions`;return(0,h.pgTable)(e,{id:(0,h.uuid)("id").primaryKey().defaultRandom(),entityId:(0,h.uuid)("entity_id").notNull(),version:(0,h.integer)("version").notNull(),locale:(0,h.varchar)("locale",{length:10}).notNull().default("_"),data:(0,h.jsonb)("data").notNull(),delta:(0,h.jsonb)("delta"),status:(0,h.varchar)("status",{length:20}),createdBy:(0,h.varchar)("created_by",{length:255}),createdByName:(0,h.varchar)("created_by_name",{length:255}),createdAt:(0,h.timestamp)("created_at",{withTimezone:!0}).notNull().defaultNow(),isAutosave:(0,h.boolean)("is_autosave").notNull().default(!1)},t=>({uniqueEntityVersionLocale:(0,h.unique)().on(t.entityId,t.version,t.locale)}))}var h,W=E(()=>{"use strict";h=require("drizzle-orm/pg-core")});var U={};D(U,{generateLocaleStatusSchema:()=>ut});function ut(r){let e=`${r.name}_locale_status`;return(0,_.pgTable)(e,{id:(0,_.uuid)("id").primaryKey().defaultRandom(),entityId:(0,_.uuid)("entity_id").notNull(),locale:(0,_.varchar)("locale",{length:10}).notNull(),status:(0,_.varchar)("status",{length:20}).notNull().default("draft"),publishedAt:(0,_.timestamp)("published_at",{withTimezone:!0})},t=>({uniqueEntityLocale:(0,_.unique)().on(t.entityId,t.locale)}))}var _,H=E(()=>{"use strict";_=require("drizzle-orm/pg-core")});var G={};D(G,{generateDraftsSchema:()=>ft});function ft(r){let e=`${r.name}_drafts`;return(0,b.pgTable)(e,{id:(0,b.uuid)("id").primaryKey().defaultRandom(),entityId:(0,b.uuid)("entity_id").notNull(),locale:(0,b.varchar)("locale",{length:10}).notNull().default("_"),data:(0,b.jsonb)("data").notNull(),createdBy:(0,b.varchar)("created_by",{length:255}).notNull(),createdByName:(0,b.varchar)("created_by_name",{length:255}),createdAt:(0,b.timestamp)("created_at",{withTimezone:!0}).notNull().defaultNow(),updatedAt:(0,b.timestamp)("updated_at",{withTimezone:!0}).notNull().defaultNow()},t=>({uniqueEntityLocale:(0,b.unique)().on(t.entityId,t.locale)}))}var b,Q=E(()=>{"use strict";b=require("drizzle-orm/pg-core")});var X={};D(X,{toolkitContentLocks:()=>mt});var k,mt,Y=E(()=>{"use strict";k=require("drizzle-orm/pg-core"),mt=(0,k.pgTable)("toolkit_content_locks",{id:(0,k.uuid)("id").primaryKey().defaultRandom(),entityType:(0,k.varchar)("entity_type",{length:100}).notNull(),entityId:(0,k.varchar)("entity_id",{length:255}).notNull(),locale:(0,k.varchar)("locale",{length:10}).notNull().default("_"),lockedBy:(0,k.varchar)("locked_by",{length:255}).notNull(),lockedByName:(0,k.varchar)("locked_by_name",{length:255}),lockedAt:(0,k.timestamp)("locked_at",{withTimezone:!0}).notNull().defaultNow(),expiresAt:(0,k.timestamp)("expires_at",{withTimezone:!0}).notNull()},r=>({uniqueEntityLock:(0,k.unique)().on(r.entityType,r.entityId,r.locale)}))});var S={};D(S,{content:()=>yt,getContentConfig:()=>gt});function gt(){if(!$)throw new Error("@murumets-ee/content plugin not initialized. Add content() to your plugins array.");return $}function yt(r){if(!r.locales||r.locales.length===0)throw new Error("content() requires at least one locale");if(!r.defaultLocale)throw new Error("content() requires a defaultLocale");if(!r.locales.some(t=>t.code===r.defaultLocale))throw new Error(`defaultLocale "${r.defaultLocale}" not found in locales: [${r.locales.map(t=>t.code).join(", ")}]`);return{name:"@murumets-ee/content",init:async t=>{$=r;let{schemaRegistry:n}=await import("@murumets-ee/db"),{generateVersionsSchema:i}=await Promise.resolve().then(()=>(W(),K)),{generateLocaleStatusSchema:a}=await Promise.resolve().then(()=>(H(),U)),{generateDraftsSchema:o}=await Promise.resolve().then(()=>(Q(),G)),{toolkitContentLocks:c}=await Promise.resolve().then(()=>(Y(),X)),{generateLayoutSchema:s,generateLayoutTranslationSchema:d}=await import("@murumets-ee/entity"),u=0,l=0,f=0,m=0;n.has("toolkit_content_locks")||n.register("toolkit_content_locks",c);for(let[y,p]of t.entities){if(p.behaviors?.some(w=>w.name==="versionable")){let w=`${y}_versions`;if(!n.has(w)){let R=i(p);n.register(w,R)}u++}let B=p.allFields;if(Object.values(B).some(w=>w.type==="blocks")){let w=`${y}_layout`;if(!n.has(w)){let V=s(p);V&&n.register(w,V)}let R=`${y}_layout_translations`;if(!n.has(R)){let V=d(p);V&&n.register(R,V)}l++}let q=p.behaviors?.some(w=>w.name==="publishable"),Z=Object.values(B).some(w=>w.translatable);if(q&&Z){let w=`${y}_locale_status`;if(!n.has(w)){let R=a(p);n.register(w,R)}f++}if(q){let w=`${y}_drafts`;if(!n.has(w)){let R=o(p);n.register(w,R)}m++}}t.logger.info({locales:r.locales.map(y=>y.code),defaultLocale:r.defaultLocale,versionableEntities:u,blockEntities:l,localeStatusEntities:f,draftEntities:m},"Content plugin initialized")}}}var $,A=E(()=>{"use strict";$=null});var ht={};D(ht,{ContentClient:()=>x,createContentClient:()=>pt});module.exports=rt(ht);var Tt=require("server-only");var ot=require("@murumets-ee/entity");function I(r){return r?r.find(t=>t.name==="versionable")?._versionableOptions??null:null}function j(r){return r.match(/\S+|\s+/g)??[]}function O(r,e){if(r===e)return r?[{type:"equal",value:r}]:[];if(!r)return[{type:"add",value:e}];if(!e)return[{type:"remove",value:r}];let t=j(r),n=j(e),i=t.length,a=n.length,o=Array.from({length:i+1},()=>new Array(a+1).fill(0));for(let l=1;l<=i;l++)for(let f=1;f<=a;f++)t[l-1]===n[f-1]?o[l][f]=o[l-1][f-1]+1:o[l][f]=Math.max(o[l-1][f],o[l][f-1]);let c=[],s=i,d=a,u=[];for(;s>0||d>0;)s>0&&d>0&&t[s-1]===n[d-1]?(u.push({type:"equal",value:t[s-1]}),s--,d--):d>0&&(s===0||o[s][d-1]>=o[s-1][d])?(u.push({type:"add",value:n[d-1]}),d--):(u.push({type:"remove",value:t[s-1]}),s--);u.reverse();for(let l of u){let f=c[c.length-1];f&&f.type===l.type?f.value+=l.value:c.push({...l})}return c}function M(r){return r.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim()}function T(r){return r==null?"":r instanceof Date?r.toISOString():typeof r=="object"?JSON.stringify(r):String(r)}function at(r,e,t,n){if(JSON.stringify(e)===JSON.stringify(t))return null;switch(n?.type??lt(e,t)){case"text":case"slug":{let a=O(T(e),T(t));return{field:r,type:"text",from:e,to:t,segments:a}}case"richtext":{let a=O(M(T(e)),M(T(t)));return{field:r,type:"richtext",from:e,to:t,segments:a}}case"number":return{field:r,type:"number",from:e,to:t};case"boolean":return{field:r,type:"boolean",from:e,to:t};case"date":return{field:r,type:"date",from:e,to:t};case"select":return{field:r,type:"select",from:e,to:t};case"media":return{field:r,type:"media",from:e,to:t};case"json":return{field:r,type:"json",from:e,to:t};case"blocks":return{field:r,type:"blocks",from:e,to:t};default:return{field:r,type:"unknown",from:e,to:t}}}function F(r,e,t){let n=new Set([...Object.keys(r),...Object.keys(e)]),i=[];for(let a of n){if(a==="id"||a==="createdAt"||a==="updatedAt")continue;let o=at(a,r[a],e[a],t?.[a]);o&&i.push(o)}return i}function lt(r,e){let t=r??e;return typeof t=="number"?"number":typeof t=="boolean"?"boolean":t instanceof Date?"date":typeof t=="string"?/^\d{4}-\d{2}-\d{2}/.test(t)?"date":"text":Array.isArray(t)?t.length>0&&typeof t[0]=="object"&&t[0]!==null&&"_block"in t[0]?"blocks":"json":typeof t=="object"?"json":"unknown"}function z(r,e){if(typeof r=="string"||typeof e=="string")return O(T(r),T(e))}function J(r){return typeof r=="object"&&r!==null&&"_block"in r&&"_id"in r&&typeof r._block=="string"&&typeof r._id=="string"}function ct(r,e){let t=new Set([...Object.keys(r),...Object.keys(e)]),n=[];for(let i of t){if(i==="_block"||i==="_id")continue;let a=r[i],o=e[i];JSON.stringify(a)!==JSON.stringify(o)&&n.push({field:i,from:a,to:o,segments:z(a,o)})}return n}function L(r,e){let t=r.filter(J),n=e.filter(J),i=new Map,a=new Map;for(let s=0;s<t.length;s++)i.set(t[s]._id,{block:t[s],index:s});for(let s=0;s<n.length;s++)a.set(n[s]._id,{block:n[s],index:s});let o=[],c=new Set;for(let[s,{block:d,index:u}]of a){c.add(s);let l=i.get(s);if(!l){o.push({blockId:s,blockType:d._block,status:"added",toIndex:u});continue}let f=l.block,m=l.index,y=ct(f,d),p=m!==u;y.length===0&&!p?o.push({blockId:s,blockType:d._block,status:"unchanged",fromIndex:m,toIndex:u}):y.length>0?o.push({blockId:s,blockType:d._block,status:"changed",fromIndex:m,toIndex:u,propDiffs:y}):o.push({blockId:s,blockType:d._block,status:"moved",fromIndex:m,toIndex:u})}for(let[s,{block:d,index:u}]of i)c.has(s)||o.push({blockId:s,blockType:d._block,status:"removed",fromIndex:u});return o}var x=class{entity;db;logger;admin=null;versionableOptions;constructor(e){this.entity=e.entity,this.db=e.db,this.logger=e.logger,this.versionableOptions=I(e.entity.behaviors)}async getAdmin(){if(!this.admin){let{AdminClient:e}=await import("@murumets-ee/entity/admin");this.admin=new e({entity:this.entity,db:this.db,logger:this.logger})}return this.admin}async create(e){let n=await(await this.getAdmin()).create(e);return this.versionableOptions&&await this.saveVersionSnapshot(n.id,n,null,!1),n}async findById(e,t){return(await this.getAdmin()).findById(e,t)}async findMany(e){return(await this.getAdmin()).findMany(e)}async update(e,t){let n=await this.getAdmin(),i=null;this.versionableOptions&&(i=await n.findById(e));let a=await n.update(e,t);if(this.versionableOptions&&i){let o=this.calculateDelta(i,a),c=await this.saveVersionSnapshot(e,a,o,!1);if(c!==void 0){let{schemaRegistry:s}=await import("@murumets-ee/db"),{eq:d}=await import("drizzle-orm"),u=s.get(this.entity.name);u&&(await this.db.update(u).set({_version:c}).where(d(u.id,e)),a._version=c)}await this.pruneVersions(e)}return a}async delete(e){return(await this.getAdmin()).delete(e)}async saveTranslation(e,t,n){return(await this.getAdmin()).saveTranslation(e,t,n)}async deleteTranslation(e,t){return(await this.getAdmin()).deleteTranslation(e,t)}async copyLayout(e,t){let{schemaRegistry:n}=await import("@murumets-ee/db"),{eq:i,and:a}=await import("drizzle-orm"),o=n.get(`${this.entity.name}_layout`);if(!o)return;let c=Array.isArray(t.to)?t.to:[t.to],s=await this.db.select().from(o).where(a(i(o.entityId,e),i(o.locale,t.from))).orderBy(o.sortOrder);if(s.length!==0){for(let d of c){await this.db.delete(o).where(a(i(o.entityId,e),i(o.locale,d)));for(let u of s)await this.db.insert(o).values({entityId:u.entityId,fieldName:u.fieldName,blockType:u.blockType,sortOrder:u.sortOrder,data:u.data,locale:d})}this.logger?.debug({entityId:e,from:t.from,to:c},"Layout copied between locales")}}async getVersions(e,t){let{schemaRegistry:n}=await import("@murumets-ee/db"),{eq:i,and:a,desc:o}=await import("drizzle-orm"),c=n.get(`${this.entity.name}_versions`);if(!c)return[];let s=t?.locale??"_",d=this.db.select().from(c).where(a(i(c.entityId,e),i(c.locale,s))).orderBy(o(c.version)).$dynamic();return t?.limit&&(d=d.limit(t.limit)),t?.offset&&(d=d.offset(t.offset)),d}async getVersion(e,t,n="_"){let{schemaRegistry:i}=await import("@murumets-ee/db"),{eq:a,and:o}=await import("drizzle-orm"),c=i.get(`${this.entity.name}_versions`);return c?(await this.db.select().from(c).where(o(a(c.entityId,e),a(c.version,t),a(c.locale,n))).limit(1))[0]??null:null}async compareVersions(e,t,n,i="_"){let[a,o]=await Promise.all([this.getVersion(e,t,i),this.getVersion(e,n,i)]);if(!a||!o)return null;let c=a.data,s=o.data,d=this.entity.allFields,u=F(c,s,d);for(let l of u)l.type==="blocks"&&Array.isArray(l.from)&&Array.isArray(l.to)&&(l.blockDiffs=L(l.from,l.to));return{diffs:u,fromVersion:a,toVersion:o}}async compareDraftWithCurrent(e,t="_"){let n=await this.getDraft(e,t);if(!n)return null;let i=await this.getAdmin(),{getContentConfig:a}=await Promise.resolve().then(()=>(A(),S)),c=a().defaultLocale,s=t==="_"?{defaultLocale:c}:{locale:t,defaultLocale:c},d=await i.findById(e,s);if(!d)return null;let u=this.entity.allFields,l={};for(let m of Object.keys(n.data))l[m]=d[m];let f=F(l,n.data,u);for(let m of f)m.type==="blocks"&&Array.isArray(m.from)&&Array.isArray(m.to)&&(m.blockDiffs=L(m.from,m.to));return{diffs:f,current:d,draft:n}}async restoreVersion(e,t){let n=await this.getVersion(e,t);if(!n)throw new Error(`Version ${t} not found for entity ${e}`);let i=n.data,{id:a,createdAt:o,createdBy:c,_version:s,_versionedAt:d,...u}=i;return(await this.getAdmin()).update(e,u)}async pruneVersions(e,t="_"){if(!this.versionableOptions)return;let{schemaRegistry:n}=await import("@murumets-ee/db"),{eq:i,and:a,desc:o,sql:c}=await import("drizzle-orm"),s=n.get(`${this.entity.name}_versions`);if(!s)return;let d=this.versionableOptions.maxPerDoc,u=await this.db.select({id:s.id}).from(s).where(a(i(s.entityId,e),i(s.locale,t))).orderBy(o(s.version)).limit(d);if(u.length<d)return;let l=u.map(f=>f.id);await this.db.delete(s).where(c`${s.entityId} = ${e} AND ${s.locale} = ${t} AND ${s.id} NOT IN (${c.join(l.map(f=>c`${f}`),c`, `)})`)}async getTranslationStatus(e){let{getContentConfig:t}=await Promise.resolve().then(()=>(A(),S)),n=t(),i=Object.entries(this.entity.allFields).filter(([l,f])=>f.translatable).map(([l])=>l);if(i.length===0)return{};let{schemaRegistry:a}=await import("@murumets-ee/db"),{eq:o}=await import("drizzle-orm"),c=a.get(`${this.entity.name}_translations`);if(!c)return{};let s=await this.db.select().from(c).where(o(c.entityId,e)),d=new Map;for(let l of s){let f=l,m={};for(let y of i)m[y]=f[y];d.set(f.locale,m)}let u={};for(let l of n.locales){if(l.code===n.defaultLocale)continue;let f=d.get(l.code)??{},m=[];for(let p of i)(f[p]===void 0||f[p]===null)&&m.push(p);let y=i.length-m.length;u[l.code]={complete:m.length===0,total:i.length,translated:y,missing:m}}return u}async getTranslationStatusBatch(e){let t=new Map;if(e.length===0)return t;let{getContentConfig:n}=await Promise.resolve().then(()=>(A(),S)),i=n(),a=Object.entries(this.entity.allFields).filter(([l,f])=>f.translatable).map(([l])=>l);if(a.length===0)return t;let{schemaRegistry:o}=await import("@murumets-ee/db"),{inArray:c}=await import("drizzle-orm"),s=o.get(`${this.entity.name}_translations`);if(!s)return t;let d=await this.db.select().from(s).where(c(s.entityId,e)),u=new Map;for(let l of d){let f=l,m=f.entityId,y=f.locale,p={};for(let v of a)p[v]=f[v];u.has(m)||u.set(m,new Map),u.get(m).set(y,p)}for(let l of e){let f=u.get(l),m={};for(let y of i.locales){if(y.code===i.defaultLocale)continue;let p=f?.get(y.code)??{},v=[];for(let C of a)(p[C]===void 0||p[C]===null)&&v.push(C);let B=a.length-v.length;m[y.code]={complete:v.length===0,total:a.length,translated:B,missing:v}}t.set(l,m)}return t}async getTranslationReport(e){let{getContentConfig:t}=await Promise.resolve().then(()=>(A(),S)),n=t(),i=e?.locale??n.locales.find(u=>u.code!==n.defaultLocale)?.code;if(!i)return{total:0,complete:0,partial:0,missing:0};let o=await(await this.getAdmin()).findMany(),c=0,s=0,d=0;for(let u of o){let f=(await this.getTranslationStatus(u.id))[i];!f||f.translated===0?d++:f.complete?c++:s++}return{total:o.length,complete:c,partial:s,missing:d}}async getLocaleStatus(e){let{schemaRegistry:t}=await import("@murumets-ee/db"),{eq:n}=await import("drizzle-orm"),i=t.get(`${this.entity.name}_locale_status`);return i?(await this.db.select().from(i).where(n(i.entityId,e))).map(o=>({locale:o.locale,status:o.status,publishedAt:o.publishedAt??null})):[]}async setLocaleStatus(e,t,n){let{getContentConfig:i}=await Promise.resolve().then(()=>(A(),S)),a=i();if(t===a.defaultLocale){let f=await this.getAdmin(),m={status:n};n==="published"&&(m.publishedAt=new Date),await f.update(e,m);return}let{schemaRegistry:o}=await import("@murumets-ee/db"),{eq:c,and:s}=await import("drizzle-orm"),d=o.get(`${this.entity.name}_locale_status`);if(!d)return;let u=n==="published"?new Date:null,[l]=await this.db.select({id:d.id}).from(d).where(s(c(d.entityId,e),c(d.locale,t))).limit(1);l?await this.db.update(d).set({status:n,publishedAt:u}).where(c(d.id,l.id)):await this.db.insert(d).values({entityId:e,locale:t,status:n,publishedAt:u})}async getLocaleStatusBatch(e){let t=new Map;if(e.length===0)return t;let{schemaRegistry:n}=await import("@murumets-ee/db"),{inArray:i}=await import("drizzle-orm"),a=n.get(`${this.entity.name}_locale_status`);if(!a)return t;let o=await this.db.select().from(a).where(i(a.entityId,e));for(let c of o){let s=c.entityId,d=c.locale;t.has(s)||t.set(s,{}),t.get(s)[d]={locale:d,status:c.status,publishedAt:c.publishedAt??null}}return t}async saveDraft(e,t,n="_",i){let{schemaRegistry:a}=await import("@murumets-ee/db"),{eq:o,and:c}=await import("drizzle-orm"),s=a.get(`${this.entity.name}_drafts`);if(!s)throw new Error(`Drafts table not found for entity "${this.entity.name}". Is the content plugin initialized?`);let d=new Date,u=i?.id??"",l=i?.name??null,[f]=await this.db.select().from(s).where(c(o(s.entityId,e),o(s.locale,n))).limit(1);if(f){let[y]=await this.db.update(s).set({data:t,updatedAt:d}).where(o(s.id,f.id)).returning();return this.toDraftEntry(y)}let[m]=await this.db.insert(s).values({entityId:e,locale:n,data:t,createdBy:u,createdByName:l,createdAt:d,updatedAt:d}).returning();return this.toDraftEntry(m)}async getDraft(e,t="_"){let{schemaRegistry:n}=await import("@murumets-ee/db"),{eq:i,and:a}=await import("drizzle-orm"),o=n.get(`${this.entity.name}_drafts`);if(!o)return null;let[c]=await this.db.select().from(o).where(a(i(o.entityId,e),i(o.locale,t))).limit(1);return c?this.toDraftEntry(c):null}async deleteDraft(e,t="_"){let{schemaRegistry:n}=await import("@murumets-ee/db"),{eq:i,and:a}=await import("drizzle-orm"),o=n.get(`${this.entity.name}_drafts`);return o?(await this.db.delete(o).where(a(i(o.entityId,e),i(o.locale,t))).returning({id:o.id})).length>0:!1}async publishDraft(e,t="_",n){let i=await this.getDraft(e,t);if(!i)throw new Error(`No draft found for entity ${e} locale ${t}`);let a=await this.getAdmin(),o=null;this.versionableOptions&&(o=await a.findById(e));let c=i.data,{id:s,createdAt:d,createdBy:u,_version:l,_versionedAt:f,...m}=c,y=await a.update(e,m);return await this.deleteDraft(e,t),this.versionableOptions&&await this.createVersionSnapshot(e,y,o,t,n),y}async hasDraft(e,t="_"){let{schemaRegistry:n}=await import("@murumets-ee/db"),{eq:i,and:a}=await import("drizzle-orm"),o=n.get(`${this.entity.name}_drafts`);if(!o)return!1;let[c]=await this.db.select({id:o.id}).from(o).where(a(i(o.entityId,e),i(o.locale,t))).limit(1);return!!c}async hasDraftBatch(e,t="_"){let n=new Set;if(e.length===0)return n;let{schemaRegistry:i}=await import("@murumets-ee/db"),{inArray:a,eq:o,and:c}=await import("drizzle-orm"),s=i.get(`${this.entity.name}_drafts`);if(!s)return n;let d=await this.db.select({entityId:s.entityId}).from(s).where(c(a(s.entityId,e),o(s.locale,t)));for(let u of d)n.add(u.entityId);return n}async createVersionSnapshot(e,t,n,i,a){if(!this.versionableOptions)return;let o=i??"_",c=n?this.calculateDelta(n,t):null,s=await this.saveVersionSnapshot(e,t,c,!1,o,a);if(s!==void 0&&o==="_"){let{schemaRegistry:d}=await import("@murumets-ee/db"),{eq:u}=await import("drizzle-orm"),l=d.get(this.entity.name);l&&await this.db.update(l).set({_version:s}).where(u(l.id,e))}await this.pruneVersions(e,o)}async saveVersionSnapshot(e,t,n,i,a="_",o){let{schemaRegistry:c}=await import("@murumets-ee/db"),{eq:s,and:d,sql:u}=await import("drizzle-orm"),l=c.get(`${this.entity.name}_versions`);if(!l)return;let[f]=await this.db.select({maxVersion:u`coalesce(max(${l.version}), 0)`}).from(l).where(d(s(l.entityId,e),s(l.locale,a))),m=(f?.maxVersion??0)+1,y=t.status??null;if(i){let[p]=await this.db.select().from(l).where(d(s(l.entityId,e),s(l.isAutosave,!0),s(l.version,m),s(l.locale,a))).limit(1);if(p)return await this.db.update(l).set({data:t,delta:n,status:y,createdAt:new Date}).where(s(l.id,p.id)),m}return await this.db.insert(l).values({entityId:e,version:m,locale:a,data:t,delta:n,status:y,createdBy:o?.id??t.updatedBy??t.createdBy??null,createdByName:o?.name??null,isAutosave:i}),m}toDraftEntry(e){return{id:e.id,entityId:e.entityId,locale:e.locale,data:e.data,createdBy:e.createdBy,createdByName:e.createdByName??null,createdAt:e.createdAt,updatedAt:e.updatedAt}}calculateDelta(e,t){let n={};for(let i of Object.keys(t))i==="id"||i.startsWith("_")||JSON.stringify(e[i])!==JSON.stringify(t[i])&&(n[i]=t[i]);return n}};async function pt(r){let{getApp:e}=await import("@murumets-ee/core"),t=e();return new x({entity:r,db:t.db.readWrite,logger:t.logger.child({content:r.name})})}0&&(module.exports={ContentClient,createContentClient});
package/dist/client.d.cts DELETED
@@ -1,215 +0,0 @@
1
- import { Logger } from '@murumets-ee/core';
2
- import { Entity, FieldToTS, FieldConfig } from '@murumets-ee/entity';
3
- import { FindManyOptions } from '@murumets-ee/entity/admin';
4
- import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
5
- import { F as FieldDiff } from './types-Cr0ifLn_.cjs';
6
- import { V as VersionEntry, D as DraftEntry, T as TranslationStatus, a as TranslationReport, L as LocalePublishStatus } from './types-BYeiE1ie.cjs';
7
-
8
- /**
9
- * ContentClient — wraps AdminClient with version history and translation status.
10
- *
11
- * Usage:
12
- * import { createContentClient } from '@murumets-ee/content/client'
13
- * const pages = createContentClient(Page)
14
- * await pages.create({ title: 'Hello', layout: [...] })
15
- */
16
-
17
- /** Value type that any entity field can hold */
18
- type EntityFieldValue = FieldToTS<FieldConfig> | null | undefined;
19
- interface ContentClientConfig {
20
- entity: Entity;
21
- db: PostgresJsDatabase;
22
- logger?: Logger;
23
- }
24
- declare class ContentClient {
25
- private entity;
26
- private db;
27
- private logger?;
28
- private admin;
29
- private versionableOptions;
30
- constructor(config: ContentClientConfig);
31
- private getAdmin;
32
- create(data: Record<string, EntityFieldValue>): Promise<{
33
- id: string;
34
- } & {} & {
35
- [x: string]: string | number | boolean | Date | Record<string, unknown> | Record<string, unknown>[] | {
36
- [key: string]: unknown;
37
- _block: string;
38
- _id: string;
39
- }[] | null | undefined;
40
- }>;
41
- findById(id: string, options?: {
42
- locale?: string;
43
- }): Promise<({
44
- id: string;
45
- } & {} & {
46
- [x: string]: string | number | boolean | Date | Record<string, unknown> | Record<string, unknown>[] | {
47
- [key: string]: unknown;
48
- _block: string;
49
- _id: string;
50
- }[] | null | undefined;
51
- }) | null>;
52
- findMany(options?: FindManyOptions): Promise<({
53
- id: string;
54
- } & {} & {
55
- [x: string]: string | number | boolean | Date | Record<string, unknown> | Record<string, unknown>[] | {
56
- [key: string]: unknown;
57
- _block: string;
58
- _id: string;
59
- }[] | null | undefined;
60
- })[]>;
61
- update(id: string, data: Record<string, EntityFieldValue>): Promise<{
62
- id: string;
63
- } & {} & {
64
- [x: string]: string | number | boolean | Date | Record<string, unknown> | Record<string, unknown>[] | {
65
- [key: string]: unknown;
66
- _block: string;
67
- _id: string;
68
- }[] | null | undefined;
69
- }>;
70
- delete(id: string): Promise<void>;
71
- saveTranslation(entityId: string, locale: string, translations: Record<string, unknown>): Promise<void>;
72
- deleteTranslation(entityId: string, locale?: string): Promise<void>;
73
- /**
74
- * Copy layout from one locale to another (for localized: true blocks).
75
- */
76
- copyLayout(entityId: string, options: {
77
- from: string;
78
- to: string | string[];
79
- }): Promise<void>;
80
- /**
81
- * List versions for an entity (newest first), filtered by locale.
82
- * Uses '_' as the locale value for default-locale snapshots.
83
- */
84
- getVersions(entityId: string, options?: {
85
- limit?: number;
86
- offset?: number;
87
- locale?: string;
88
- }): Promise<VersionEntry[]>;
89
- /**
90
- * Get a specific version snapshot.
91
- */
92
- getVersion(entityId: string, version: number, locale?: string): Promise<VersionEntry | null>;
93
- /**
94
- * Compare two versions and return field-level diff.
95
- *
96
- * Returns structured diffs with word-level segments for text fields
97
- * and structural block diffs for blocks fields.
98
- */
99
- compareVersions(entityId: string, v1: number, v2: number, locale?: string): Promise<{
100
- diffs: FieldDiff[];
101
- fromVersion: VersionEntry;
102
- toVersion: VersionEntry;
103
- } | null>;
104
- /**
105
- * Compare the current draft with the live entity (or a specific version).
106
- * Returns field-level diffs between the current published data and the draft.
107
- */
108
- compareDraftWithCurrent(entityId: string, locale?: string): Promise<{
109
- diffs: FieldDiff[];
110
- current: Record<string, unknown>;
111
- draft: DraftEntry;
112
- } | null>;
113
- /**
114
- * Restore an entity to a previous version.
115
- */
116
- restoreVersion(entityId: string, version: number): Promise<{
117
- id: string;
118
- } & {} & {
119
- [x: string]: string | number | boolean | Date | Record<string, unknown> | Record<string, unknown>[] | {
120
- [key: string]: unknown;
121
- _block: string;
122
- _id: string;
123
- }[] | null | undefined;
124
- }>;
125
- /**
126
- * Enforce maxPerDoc retention by deleting oldest versions for a locale.
127
- */
128
- pruneVersions(entityId: string, locale?: string): Promise<void>;
129
- /**
130
- * Get translation status for an entity — per-locale completion report.
131
- */
132
- getTranslationStatus(entityId: string): Promise<TranslationStatus>;
133
- /**
134
- * Get translation status for multiple entities in a single query.
135
- * Returns a map of entityId → TranslationStatus (O(1) DB roundtrips).
136
- */
137
- getTranslationStatusBatch(entityIds: string[]): Promise<Map<string, TranslationStatus>>;
138
- /**
139
- * Get translation report across all entities of this type.
140
- */
141
- getTranslationReport(options?: {
142
- locale?: string;
143
- }): Promise<TranslationReport>;
144
- /**
145
- * Get per-locale publish status for an entity.
146
- * Returns status for all non-default locales that have explicit overrides.
147
- * Missing locale = inherits base entity status.
148
- */
149
- getLocaleStatus(entityId: string): Promise<LocalePublishStatus[]>;
150
- /**
151
- * Set per-locale publish status. Upserts into locale_status table.
152
- * When locale === defaultLocale, updates the base entity status instead.
153
- */
154
- setLocaleStatus(entityId: string, locale: string, status: 'draft' | 'published'): Promise<void>;
155
- /**
156
- * Get per-locale publish status for multiple entities in a single query.
157
- * Returns a map of entityId → locale → LocalePublishStatus.
158
- */
159
- getLocaleStatusBatch(entityIds: string[]): Promise<Map<string, Record<string, LocalePublishStatus>>>;
160
- /**
161
- * Save (upsert) a draft for an entity+locale.
162
- * One draft per entity+locale — overwrites any existing draft.
163
- */
164
- saveDraft(entityId: string, data: Record<string, unknown>, locale?: string, user?: {
165
- id: string;
166
- name?: string;
167
- }): Promise<DraftEntry>;
168
- /**
169
- * Get the draft for an entity+locale, or null if none exists.
170
- */
171
- getDraft(entityId: string, locale?: string): Promise<DraftEntry | null>;
172
- /**
173
- * Delete (discard) a draft for an entity+locale.
174
- */
175
- deleteDraft(entityId: string, locale?: string): Promise<boolean>;
176
- /**
177
- * Publish a draft: apply draft data to the live entity, then delete the draft.
178
- * Runs in a transaction to ensure atomicity.
179
- */
180
- publishDraft(entityId: string, locale?: string, user?: {
181
- id: string;
182
- name?: string;
183
- }): Promise<Record<string, unknown>>;
184
- /**
185
- * Quick existence check for list badges — does a draft exist?
186
- */
187
- hasDraft(entityId: string, locale?: string): Promise<boolean>;
188
- /**
189
- * Check draft existence for multiple entities in one query.
190
- * Returns a set of entity IDs that have drafts.
191
- */
192
- hasDraftBatch(entityIds: string[], locale?: string): Promise<Set<string>>;
193
- /**
194
- * Create a version snapshot for an entity after an external update.
195
- * Use this when the update was performed by AdminClient directly
196
- * (e.g., the admin API handler) rather than through ContentClient.update().
197
- *
198
- * @param locale - The locale being edited. Use undefined or '_' for the default locale.
199
- * @param user - The user who made the change (id + name for display).
200
- */
201
- createVersionSnapshot(entityId: string, currentData: Record<string, unknown>, previousData?: Record<string, unknown> | null, locale?: string, user?: {
202
- id: string;
203
- name?: string;
204
- }): Promise<void>;
205
- private saveVersionSnapshot;
206
- private toDraftEntry;
207
- private calculateDelta;
208
- }
209
- /**
210
- * Factory — creates a ContentClient for an entity.
211
- * Must be called after createApp().
212
- */
213
- declare function createContentClient(entity: Entity): Promise<ContentClient>;
214
-
215
- export { ContentClient, type ContentClientConfig, createContentClient };
package/dist/index.cjs DELETED
@@ -1 +0,0 @@
1
- "use strict";var m=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var I=Object.prototype.hasOwnProperty;var R=(e,n)=>{for(var t in n)m(e,t,{get:n[t],enumerable:!0})},W=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of E(n))!I.call(e,o)&&o!==t&&m(e,o,{get:()=>n[o],enumerable:!(i=q(n,o))||i.enumerable});return e};var C=e=>W(m({},"__esModule",{value:!0}),e);var K={};R(K,{WORKFLOW_STATES:()=>x,defineBlock:()=>D,diffBlocks:()=>A,diffField:()=>_,diffFields:()=>T,diffStringValues:()=>g,diffText:()=>p,getVersionableOptions:()=>S,versionable:()=>F,workflowable:()=>v});module.exports=C(K);var h=require("@murumets-ee/entity"),L={maxPerDoc:50,autosave:!1};function F(e){let n={...L,...e};return{name:"versionable",fields:{_version:h.field.number({required:!0,default:1,integer:!0}),_versionedAt:h.field.date()},hooks:{beforeCreate:async i=>(i._version=1,i._versionedAt=new Date,i),beforeUpdate:async(i,o)=>(o._versionedAt=new Date,o)},_versionableOptions:n}}function S(e){return e?e.find(t=>t.name==="versionable")?._versionableOptions??null:null}var y=require("@murumets-ee/entity"),x=["draft","in_review","approved","rejected","published"];function v(){return{name:"workflowable",fields:{_workflowStatus:y.field.select({options:x,default:"draft",indexed:!0,required:!0}),_workflowAssignee:y.field.text({required:!1}),_workflowNote:y.field.text({required:!1}),_workflowUpdatedAt:y.field.date()},hooks:{beforeCreate:async e=>(e._workflowStatus="draft",e._workflowUpdatedAt=new Date,e)}}}function D(e){if(!e.slug||!e.slug.match(/^[a-z][a-z0-9-]*$/))throw new Error(`Block slug must be lowercase alphanumeric with hyphens, got: "${e.slug}"`);if(!e.label)throw new Error(`Block label is required for slug: "${e.slug}"`);if(!e.fields||Object.keys(e.fields).length===0)throw new Error(`Block "${e.slug}" must have at least one field`);return{slug:e.slug,label:e.label,fields:e.fields}}function B(e){return e.match(/\S+|\s+/g)??[]}function p(e,n){if(e===n)return e?[{type:"equal",value:e}]:[];if(!e)return[{type:"add",value:n}];if(!n)return[{type:"remove",value:e}];let t=B(e),i=B(n),o=t.length,s=i.length,l=Array.from({length:o+1},()=>new Array(s+1).fill(0));for(let u=1;u<=o;u++)for(let c=1;c<=s;c++)t[u-1]===i[c-1]?l[u][c]=l[u-1][c-1]+1:l[u][c]=Math.max(l[u-1][c],l[u][c-1]);let a=[],r=o,f=s,d=[];for(;r>0||f>0;)r>0&&f>0&&t[r-1]===i[f-1]?(d.push({type:"equal",value:t[r-1]}),r--,f--):f>0&&(r===0||l[r][f-1]>=l[r-1][f])?(d.push({type:"add",value:i[f-1]}),f--):(d.push({type:"remove",value:t[r-1]}),r--);d.reverse();for(let u of d){let c=a[a.length-1];c&&c.type===u.type?c.value+=u.value:a.push({...u})}return a}function O(e){return e.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim()}function k(e){return e==null?"":e instanceof Date?e.toISOString():typeof e=="object"?JSON.stringify(e):String(e)}function _(e,n,t,i){if(JSON.stringify(n)===JSON.stringify(t))return null;switch(i?.type??U(n,t)){case"text":case"slug":{let s=p(k(n),k(t));return{field:e,type:"text",from:n,to:t,segments:s}}case"richtext":{let s=p(O(k(n)),O(k(t)));return{field:e,type:"richtext",from:n,to:t,segments:s}}case"number":return{field:e,type:"number",from:n,to:t};case"boolean":return{field:e,type:"boolean",from:n,to:t};case"date":return{field:e,type:"date",from:n,to:t};case"select":return{field:e,type:"select",from:n,to:t};case"media":return{field:e,type:"media",from:n,to:t};case"json":return{field:e,type:"json",from:n,to:t};case"blocks":return{field:e,type:"blocks",from:n,to:t};default:return{field:e,type:"unknown",from:n,to:t}}}function T(e,n,t){let i=new Set([...Object.keys(e),...Object.keys(n)]),o=[];for(let s of i){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;let l=_(s,e[s],n[s],t?.[s]);l&&o.push(l)}return o}function U(e,n){let t=e??n;return typeof t=="number"?"number":typeof t=="boolean"?"boolean":t instanceof Date?"date":typeof t=="string"?/^\d{4}-\d{2}-\d{2}/.test(t)?"date":"text":Array.isArray(t)?t.length>0&&typeof t[0]=="object"&&t[0]!==null&&"_block"in t[0]?"blocks":"json":typeof t=="object"?"json":"unknown"}function g(e,n){if(typeof e=="string"||typeof n=="string")return p(k(e),k(n))}function j(e){return typeof e=="object"&&e!==null&&"_block"in e&&"_id"in e&&typeof e._block=="string"&&typeof e._id=="string"}function J(e,n){let t=new Set([...Object.keys(e),...Object.keys(n)]),i=[];for(let o of t){if(o==="_block"||o==="_id")continue;let s=e[o],l=n[o];JSON.stringify(s)!==JSON.stringify(l)&&i.push({field:o,from:s,to:l,segments:g(s,l)})}return i}function A(e,n){let t=e.filter(j),i=n.filter(j),o=new Map,s=new Map;for(let r=0;r<t.length;r++)o.set(t[r]._id,{block:t[r],index:r});for(let r=0;r<i.length;r++)s.set(i[r]._id,{block:i[r],index:r});let l=[],a=new Set;for(let[r,{block:f,index:d}]of s){a.add(r);let u=o.get(r);if(!u){l.push({blockId:r,blockType:f._block,status:"added",toIndex:d});continue}let c=u.block,b=u.index,w=J(c,f),V=b!==d;w.length===0&&!V?l.push({blockId:r,blockType:f._block,status:"unchanged",fromIndex:b,toIndex:d}):w.length>0?l.push({blockId:r,blockType:f._block,status:"changed",fromIndex:b,toIndex:d,propDiffs:w}):l.push({blockId:r,blockType:f._block,status:"moved",fromIndex:b,toIndex:d})}for(let[r,{block:f,index:d}]of o)a.has(r)||l.push({blockId:r,blockType:f._block,status:"removed",fromIndex:d});return l}0&&(module.exports={WORKFLOW_STATES,defineBlock,diffBlocks,diffField,diffFields,diffStringValues,diffText,getVersionableOptions,versionable,workflowable});
package/dist/index.d.cts DELETED
@@ -1,142 +0,0 @@
1
- import { Behavior, NumberField, DateField, SelectField, TextField, FieldConfig } from '@murumets-ee/entity';
2
- import { b as VersionableOptions, B as BlockDefinition } from './types-BYeiE1ie.cjs';
3
- export { C as ContentConfig, D as DraftEntry, I as InferBlockData, c as InferBlocksUnion, d as LocaleConfig, e as LockInfo, f as TranslationFieldStatus, a as TranslationReport, T as TranslationStatus, V as VersionEntry } from './types-BYeiE1ie.cjs';
4
- import { B as BlockDiffEntry, F as FieldDiff, D as DiffSegment } from './types-Cr0ifLn_.cjs';
5
- export { a as BlockDiffStatus, P as PropDiff } from './types-Cr0ifLn_.cjs';
6
-
7
- /**
8
- * Versionable behavior — full version history with snapshots.
9
- *
10
- * Extends the concept of revisionable() (which only tracks a counter)
11
- * with actual version snapshots stored in {entity}_versions table.
12
- *
13
- * The behavior itself adds fields + hooks for version tracking.
14
- * Actual snapshot persistence happens in ContentClient (which has DB access).
15
- *
16
- * Options:
17
- * - maxPerDoc: Maximum versions kept per document (default: 50)
18
- * - autosave: Enable smart autosave (default: false)
19
- */
20
-
21
- type VersionableFields = {
22
- _version: NumberField & {
23
- required: true;
24
- };
25
- _versionedAt: DateField;
26
- };
27
- declare function versionable(options?: VersionableOptions): Behavior<VersionableFields>;
28
- /**
29
- * Extract versionable options from an entity's behaviors
30
- */
31
- declare function getVersionableOptions(behaviors?: Behavior[]): Required<VersionableOptions> | null;
32
-
33
- /**
34
- * Workflowable behavior — editorial workflow with approval gates.
35
- *
36
- * Adds workflow status tracking fields to an entity. Works alongside
37
- * `publishable()` — the workflow status tracks the editorial pipeline,
38
- * while publishable's `status` remains the public-facing state.
39
- *
40
- * Key invariant: `status` can only transition to 'published' when
41
- * `_workflowStatus === 'approved'` (unless the user has direct `publish`
42
- * permission, which bypasses the workflow).
43
- *
44
- * Workflow states:
45
- * - draft → in_review (submit for review, requires 'update')
46
- * - in_review → approved (approve, requires 'publish')
47
- * - in_review → rejected (reject with note, requires 'publish')
48
- * - approved → published (publish, requires 'publish')
49
- * - rejected → in_review (resubmit, requires 'update')
50
- * - published → draft (unpublish, requires 'publish')
51
- */
52
-
53
- declare const WORKFLOW_STATES: readonly ["draft", "in_review", "approved", "rejected", "published"];
54
- type WorkflowState = (typeof WORKFLOW_STATES)[number];
55
- type WorkflowableFields = {
56
- _workflowStatus: SelectField & {
57
- required: true;
58
- };
59
- _workflowAssignee: TextField;
60
- _workflowNote: TextField;
61
- _workflowUpdatedAt: DateField;
62
- };
63
- declare function workflowable(): Behavior<WorkflowableFields>;
64
-
65
- /**
66
- * Block definition API
67
- *
68
- * defineBlock() creates a reusable content block with typed fields.
69
- * Uses `const F` generic to preserve literal field types for inference.
70
- *
71
- * Blocks are NOT entities — they lack independent identity, CRUD, and access control.
72
- * They exist only as embedded data within a parent entity's blocks field.
73
- *
74
- * @example
75
- * const HeroBlock = defineBlock({
76
- * slug: 'hero',
77
- * label: 'Hero Section',
78
- * fields: {
79
- * heading: field.text({ required: true, translatable: true }),
80
- * background: field.media({ accept: ['image/*'] }),
81
- * },
82
- * })
83
- */
84
-
85
- declare function defineBlock<const F extends Record<string, FieldConfig>>(definition: {
86
- slug: string;
87
- label: string;
88
- fields: F;
89
- }): BlockDefinition<F>;
90
-
91
- /**
92
- * Structural diff for Puck block arrays.
93
- *
94
- * Blocks are identified by `_id`. The algorithm detects:
95
- * - Added blocks (new _id in target)
96
- * - Removed blocks (missing _id in target)
97
- * - Moved blocks (same _id, different position)
98
- * - Changed blocks (same _id, different prop values)
99
- * - Unchanged blocks
100
- */
101
-
102
- /**
103
- * Compute structural diff between two block arrays.
104
- *
105
- * Each block is identified by its `_id` field. Position changes,
106
- * additions, removals, and prop-level changes are all detected.
107
- */
108
- declare function diffBlocks(fromBlocks: unknown[], toBlocks: unknown[]): BlockDiffEntry[];
109
-
110
- /**
111
- * Field-level diff — dispatches to the appropriate diff strategy per field type.
112
- */
113
-
114
- /**
115
- * Compute diff for a single field, using the field's type to determine
116
- * the best diff strategy.
117
- */
118
- declare function diffField(fieldName: string, from: unknown, to: unknown, fieldConfig?: FieldConfig): FieldDiff | null;
119
- /**
120
- * Diff all fields between two version snapshots.
121
- * Pass fieldConfigs to get type-aware diffs; without them, types are inferred.
122
- */
123
- declare function diffFields(from: Record<string, unknown>, to: Record<string, unknown>, fieldConfigs?: Record<string, FieldConfig>): FieldDiff[];
124
- /** Diff two string values and return segments (used by block-diff for string props). */
125
- declare function diffStringValues(from: unknown, to: unknown): DiffSegment[] | undefined;
126
-
127
- /**
128
- * Word-level text diff using a simplified Myers algorithm.
129
- *
130
- * Splits text into words (preserving whitespace), computes the longest common
131
- * subsequence, and returns an array of diff segments.
132
- */
133
-
134
- /**
135
- * Compute word-level diff between two strings.
136
- *
137
- * Uses a simple LCS (dynamic programming) approach which is fine for
138
- * the text sizes we deal with (entity field values, not source code).
139
- */
140
- declare function diffText(from: string, to: string): DiffSegment[];
141
-
142
- export { BlockDefinition, BlockDiffEntry, DiffSegment, FieldDiff, VersionableOptions, WORKFLOW_STATES, type WorkflowState, type WorkflowableFields, defineBlock, diffBlocks, diffField, diffFields, diffStringValues, diffText, getVersionableOptions, versionable, workflowable };
@@ -1 +0,0 @@
1
- "use strict";var m=Object.create;var p=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var f=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty;var T=(n,e)=>{for(var s in e)p(n,s,{get:e[s],enumerable:!0})},y=(n,e,s,c)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of h(e))!A.call(n,i)&&i!==s&&p(n,i,{get:()=>e[i],enumerable:!(c=b(e,i))||c.enumerable});return n};var g=(n,e,s)=>(s=n!=null?m(f(n)):{},y(e||!n||!n.__esModule?p(s,"default",{value:n,enumerable:!0}):s,n)),x=n=>y(p({},"__esModule",{value:!0}),n);var D={};T(D,{LockService:()=>w,createLockService:()=>B});module.exports=x(D);var L=require("server-only"),k=5,w=class{db;constructor(e){this.db=e.db}async getTable(){let{schemaRegistry:e}=await import("@murumets-ee/db");return e.get("toolkit_content_locks")}async acquireLock(e,s,c,i){let{eq:r,and:o,lt:a}=await import("drizzle-orm"),t=await this.getTable();if(!t)return{acquired:!0};let l=new Date,u=new Date(l.getTime()+k*60*1e3);await this.db.delete(t).where(o(r(t.entityType,e),r(t.entityId,s),r(t.locale,c),a(t.expiresAt,l)));let[d]=await this.db.select().from(t).where(o(r(t.entityType,e),r(t.entityId,s),r(t.locale,c))).limit(1);return d?d.lockedBy===i.id?(await this.db.update(t).set({expiresAt:u,lockedAt:l}).where(r(t.id,d.id)),{acquired:!0}):{acquired:!1,lock:{lockedBy:d.lockedBy,lockedByName:d.lockedByName??null,lockedAt:d.lockedAt,expiresAt:d.expiresAt}}:(await this.db.insert(t).values({entityType:e,entityId:s,locale:c,lockedBy:i.id,lockedByName:i.name??null,lockedAt:l,expiresAt:u}),{acquired:!0})}async renewLock(e,s,c,i){let{eq:r,and:o,gte:a}=await import("drizzle-orm"),t=await this.getTable();if(!t)return!0;let l=new Date,u=new Date(l.getTime()+k*60*1e3);return(await this.db.update(t).set({expiresAt:u}).where(o(r(t.entityType,e),r(t.entityId,s),r(t.locale,c),r(t.lockedBy,i),a(t.expiresAt,l))).returning({id:t.id})).length>0}async releaseLock(e,s,c,i){let{eq:r,and:o}=await import("drizzle-orm"),a=await this.getTable();return a?(await this.db.delete(a).where(o(r(a.entityType,e),r(a.entityId,s),r(a.locale,c),r(a.lockedBy,i))).returning({id:a.id})).length>0:!0}async forceReleaseLock(e,s,c){let{eq:i,and:r}=await import("drizzle-orm"),o=await this.getTable();return o?(await this.db.delete(o).where(r(i(o.entityType,e),i(o.entityId,s),i(o.locale,c))).returning({id:o.id})).length>0:!0}async getLock(e,s,c){let{eq:i,and:r,gte:o}=await import("drizzle-orm"),a=await this.getTable();if(!a)return null;let t=new Date,[l]=await this.db.select().from(a).where(r(i(a.entityType,e),i(a.entityId,s),i(a.locale,c),o(a.expiresAt,t))).limit(1);return l?{lockedBy:l.lockedBy,lockedByName:l.lockedByName??null,lockedAt:l.lockedAt,expiresAt:l.expiresAt}:null}};async function B(){let{getApp:n}=await import("@murumets-ee/core"),e=n();return new w({db:e.db.readWrite})}0&&(module.exports={LockService,createLockService});
@@ -1,61 +0,0 @@
1
- import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
2
- import { e as LockInfo } from './types-BYeiE1ie.cjs';
3
- import '@murumets-ee/entity';
4
-
5
- /**
6
- * Content lock service — pessimistic locking for entity editing.
7
- *
8
- * Prevents concurrent edit conflicts by allowing only one editor at a time
9
- * per entity+locale combination. Locks expire after 5 minutes and must
10
- * be renewed via heartbeat.
11
- */
12
-
13
- interface LockServiceConfig {
14
- db: PostgresJsDatabase;
15
- }
16
- declare class LockService {
17
- private db;
18
- constructor(config: LockServiceConfig);
19
- private getTable;
20
- /**
21
- * Acquire a lock on an entity+locale.
22
- *
23
- * - Deletes expired locks first
24
- * - Attempts INSERT; on conflict checks if same user (re-entrant → renew)
25
- * - Returns { acquired: true } or { acquired: false, lock: LockInfo }
26
- */
27
- acquireLock(entityType: string, entityId: string, locale: string, user: {
28
- id: string;
29
- name?: string;
30
- }): Promise<{
31
- acquired: true;
32
- } | {
33
- acquired: false;
34
- lock: LockInfo;
35
- }>;
36
- /**
37
- * Renew an existing lock (heartbeat).
38
- * Only succeeds if the caller holds the lock and it hasn't expired.
39
- */
40
- renewLock(entityType: string, entityId: string, locale: string, userId: string): Promise<boolean>;
41
- /**
42
- * Release a lock. Only the lock holder can release their own lock.
43
- */
44
- releaseLock(entityType: string, entityId: string, locale: string, userId: string): Promise<boolean>;
45
- /**
46
- * Force-release a lock regardless of who holds it.
47
- * Admin-only operation — must be audit-logged by the caller.
48
- */
49
- forceReleaseLock(entityType: string, entityId: string, locale: string): Promise<boolean>;
50
- /**
51
- * Get the current lock for an entity+locale.
52
- * Returns null if no lock or lock has expired.
53
- */
54
- getLock(entityType: string, entityId: string, locale: string): Promise<LockInfo | null>;
55
- }
56
- /**
57
- * Factory — creates a LockService using the app's DB connection.
58
- */
59
- declare function createLockService(): Promise<LockService>;
60
-
61
- export { LockService, type LockServiceConfig, createLockService };
package/dist/plugin.cjs DELETED
@@ -1 +0,0 @@
1
- "use strict";var P=Object.create;var h=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var O=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var p=(t,a)=>()=>(t&&(a=t(t=0)),a);var f=(t,a)=>{for(var e in a)h(t,e,{get:a[e],enumerable:!0})},v=(t,a,e,i)=>{if(a&&typeof a=="object"||typeof a=="function")for(let m of F(a))!G.call(t,m)&&m!==e&&h(t,m,{get:()=>a[m],enumerable:!(i=D(a,m))||i.enumerable});return t};var E=(t,a,e)=>(e=t!=null?P(O(t)):{},v(a||!t||!t.__esModule?h(e,"default",{value:t,enumerable:!0}):e,t)),H=t=>v(h({},"__esModule",{value:!0}),t);var C={};f(C,{generateVersionsSchema:()=>J});function J(t){let a=`${t.name}_versions`;return(0,o.pgTable)(a,{id:(0,o.uuid)("id").primaryKey().defaultRandom(),entityId:(0,o.uuid)("entity_id").notNull(),version:(0,o.integer)("version").notNull(),locale:(0,o.varchar)("locale",{length:10}).notNull().default("_"),data:(0,o.jsonb)("data").notNull(),delta:(0,o.jsonb)("delta"),status:(0,o.varchar)("status",{length:20}),createdBy:(0,o.varchar)("created_by",{length:255}),createdByName:(0,o.varchar)("created_by_name",{length:255}),createdAt:(0,o.timestamp)("created_at",{withTimezone:!0}).notNull().defaultNow(),isAutosave:(0,o.boolean)("is_autosave").notNull().default(!1)},e=>({uniqueEntityVersionLocale:(0,o.unique)().on(e.entityId,e.version,e.locale)}))}var o,L=p(()=>{"use strict";o=require("drizzle-orm/pg-core")});var S={};f(S,{generateLocaleStatusSchema:()=>M});function M(t){let a=`${t.name}_locale_status`;return(0,r.pgTable)(a,{id:(0,r.uuid)("id").primaryKey().defaultRandom(),entityId:(0,r.uuid)("entity_id").notNull(),locale:(0,r.varchar)("locale",{length:10}).notNull(),status:(0,r.varchar)("status",{length:20}).notNull().default("draft"),publishedAt:(0,r.timestamp)("published_at",{withTimezone:!0})},e=>({uniqueEntityLocale:(0,r.unique)().on(e.entityId,e.locale)}))}var r,q=p(()=>{"use strict";r=require("drizzle-orm/pg-core")});var x={};f(x,{generateDraftsSchema:()=>Q});function Q(t){let a=`${t.name}_drafts`;return(0,l.pgTable)(a,{id:(0,l.uuid)("id").primaryKey().defaultRandom(),entityId:(0,l.uuid)("entity_id").notNull(),locale:(0,l.varchar)("locale",{length:10}).notNull().default("_"),data:(0,l.jsonb)("data").notNull(),createdBy:(0,l.varchar)("created_by",{length:255}).notNull(),createdByName:(0,l.varchar)("created_by_name",{length:255}),createdAt:(0,l.timestamp)("created_at",{withTimezone:!0}).notNull().defaultNow(),updatedAt:(0,l.timestamp)("updated_at",{withTimezone:!0}).notNull().defaultNow()},e=>({uniqueEntityLocale:(0,l.unique)().on(e.entityId,e.locale)}))}var l,$=p(()=>{"use strict";l=require("drizzle-orm/pg-core")});var z={};f(z,{toolkitContentLocks:()=>U});var s,U,A=p(()=>{"use strict";s=require("drizzle-orm/pg-core"),U=(0,s.pgTable)("toolkit_content_locks",{id:(0,s.uuid)("id").primaryKey().defaultRandom(),entityType:(0,s.varchar)("entity_type",{length:100}).notNull(),entityId:(0,s.varchar)("entity_id",{length:255}).notNull(),locale:(0,s.varchar)("locale",{length:10}).notNull().default("_"),lockedBy:(0,s.varchar)("locked_by",{length:255}).notNull(),lockedByName:(0,s.varchar)("locked_by_name",{length:255}),lockedAt:(0,s.timestamp)("locked_at",{withTimezone:!0}).notNull().defaultNow(),expiresAt:(0,s.timestamp)("expires_at",{withTimezone:!0}).notNull()},t=>({uniqueEntityLock:(0,s.unique)().on(t.entityType,t.entityId,t.locale)}))});var Y={};f(Y,{content:()=>X,getContentConfig:()=>W});module.exports=H(Y);var g=null;function W(){if(!g)throw new Error("@murumets-ee/content plugin not initialized. Add content() to your plugins array.");return g}function X(t){if(!t.locales||t.locales.length===0)throw new Error("content() requires at least one locale");if(!t.defaultLocale)throw new Error("content() requires a defaultLocale");if(!t.locales.some(e=>e.code===t.defaultLocale))throw new Error(`defaultLocale "${t.defaultLocale}" not found in locales: [${t.locales.map(e=>e.code).join(", ")}]`);return{name:"@murumets-ee/content",init:async e=>{g=t;let{schemaRegistry:i}=await import("@murumets-ee/db"),{generateVersionsSchema:m}=await Promise.resolve().then(()=>(L(),C)),{generateLocaleStatusSchema:B}=await Promise.resolve().then(()=>(q(),S)),{generateDraftsSchema:I}=await Promise.resolve().then(()=>($(),x)),{toolkitContentLocks:j}=await Promise.resolve().then(()=>(A(),z)),{generateLayoutSchema:R,generateLayoutTranslationSchema:V}=await import("@murumets-ee/entity"),_=0,b=0,N=0,w=0;i.has("toolkit_content_locks")||i.register("toolkit_content_locks",j);for(let[d,u]of e.entities){if(u.behaviors?.some(n=>n.name==="versionable")){let n=`${d}_versions`;if(!i.has(n)){let c=m(u);i.register(n,c)}_++}let k=u.allFields;if(Object.values(k).some(n=>n.type==="blocks")){let n=`${d}_layout`;if(!i.has(n)){let y=R(u);y&&i.register(n,y)}let c=`${d}_layout_translations`;if(!i.has(c)){let y=V(u);y&&i.register(c,y)}b++}let T=u.behaviors?.some(n=>n.name==="publishable"),K=Object.values(k).some(n=>n.translatable);if(T&&K){let n=`${d}_locale_status`;if(!i.has(n)){let c=B(u);i.register(n,c)}N++}if(T){let n=`${d}_drafts`;if(!i.has(n)){let c=I(u);i.register(n,c)}w++}}e.logger.info({locales:t.locales.map(d=>d.code),defaultLocale:t.defaultLocale,versionableEntities:_,blockEntities:b,localeStatusEntities:N,draftEntities:w},"Content plugin initialized")}}}0&&(module.exports={content,getContentConfig});
package/dist/plugin.d.cts DELETED
@@ -1,33 +0,0 @@
1
- import { Plugin } from '@murumets-ee/core';
2
- import { C as ContentConfig } from './types-BYeiE1ie.cjs';
3
- import '@murumets-ee/entity';
4
-
5
- /**
6
- * Content plugin — registers locale configuration and version schemas.
7
- *
8
- * Usage:
9
- * import { content } from '@murumets-ee/content/plugin'
10
- *
11
- * export default defineConfig({
12
- * plugins: [
13
- * content({
14
- * locales: [
15
- * { code: 'en', label: 'English' },
16
- * { code: 'de', label: 'German' },
17
- * ],
18
- * defaultLocale: 'en',
19
- * }),
20
- * ],
21
- * })
22
- */
23
-
24
- /**
25
- * Get the content configuration. Throws if plugin not initialized.
26
- */
27
- declare function getContentConfig(): ContentConfig;
28
- /**
29
- * Content plugin factory.
30
- */
31
- declare function content(config: ContentConfig): Plugin;
32
-
33
- export { content, getContentConfig };
@@ -1 +0,0 @@
1
- "use strict";var g=Object.create;var s=Object.defineProperty;var l=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var c=Object.getPrototypeOf,d=Object.prototype.hasOwnProperty;var m=(e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})},u=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of p(t))!d.call(e,n)&&n!==r&&s(e,n,{get:()=>t[n],enumerable:!(i=l(t,n))||i.enumerable});return e};var o=(e,t,r)=>(r=e!=null?g(c(e)):{},u(t||!e||!e.__esModule?s(r,"default",{value:e,enumerable:!0}):r,e)),h=e=>u(s({},"__esModule",{value:!0}),e);var q={};m(q,{ContentQueryClient:()=>y,createContentQueryClient:()=>f});module.exports=h(q);var y=class{entity;db;logger;query=null;constructor(t){this.entity=t.entity,this.db=t.db,this.logger=t.logger}async getQuery(){if(!this.query){let{QueryClient:t}=await import("@murumets-ee/entity/query");this.query=new t({entity:this.entity,db:this.db,logger:this.logger})}return this.query}async findById(t,r){return(await this.getQuery()).findById(t,r)}async findBySlug(t,r){let{schemaRegistry:i}=await import("@murumets-ee/db"),{eq:n}=await import("drizzle-orm"),a=i.get(this.entity.name);return!a||!a.slug?null:(await(await this.getQuery()).findMany({where:n(a.slug,t),limit:1,locale:r?.locale}))[0]??null}async findMany(t){return(await this.getQuery()).findMany(t)}async count(t){return(await this.getQuery()).count(t)}};async function f(e){let{getApp:t}=await import("@murumets-ee/core"),r=t();return new y({entity:e,db:r.db.readOnly,logger:r.logger.child({content:e.name})})}0&&(module.exports={ContentQueryClient,createContentQueryClient});
@@ -1,67 +0,0 @@
1
- import { Logger } from '@murumets-ee/core';
2
- import { Entity } from '@murumets-ee/entity';
3
- import { FindByIdOptions, FindManyOptions, CountOptions } from '@murumets-ee/entity/query';
4
- import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
5
-
6
- /**
7
- * ContentQueryClient — read-only content queries, safe for client bundles.
8
- *
9
- * Usage:
10
- * import { createContentQueryClient } from '@murumets-ee/content/query'
11
- * const pages = createContentQueryClient(Page)
12
- * const page = await pages.findBySlug('about', { locale: 'de' })
13
- */
14
-
15
- interface ContentQueryClientConfig {
16
- entity: Entity;
17
- db: PostgresJsDatabase;
18
- logger?: Logger;
19
- }
20
- declare class ContentQueryClient {
21
- private entity;
22
- private db;
23
- private logger?;
24
- private query;
25
- constructor(config: ContentQueryClientConfig);
26
- private getQuery;
27
- findById(id: string, options?: FindByIdOptions): Promise<({
28
- id: string;
29
- } & {} & {
30
- [x: string]: string | number | boolean | Date | Record<string, unknown> | Record<string, unknown>[] | {
31
- [key: string]: unknown;
32
- _block: string;
33
- _id: string;
34
- }[] | null | undefined;
35
- }) | null>;
36
- /**
37
- * Find entity by slug — convenience for slug-based lookups.
38
- */
39
- findBySlug(slug: string, options?: {
40
- locale?: string;
41
- }): Promise<({
42
- id: string;
43
- } & {} & {
44
- [x: string]: string | number | boolean | Date | Record<string, unknown> | Record<string, unknown>[] | {
45
- [key: string]: unknown;
46
- _block: string;
47
- _id: string;
48
- }[] | null | undefined;
49
- }) | null>;
50
- findMany(options?: FindManyOptions): Promise<({
51
- id: string;
52
- } & {} & {
53
- [x: string]: string | number | boolean | Date | Record<string, unknown> | Record<string, unknown>[] | {
54
- [key: string]: unknown;
55
- _block: string;
56
- _id: string;
57
- }[] | null | undefined;
58
- })[]>;
59
- count(options?: CountOptions): Promise<number>;
60
- }
61
- /**
62
- * Factory — creates a ContentQueryClient for an entity.
63
- * Must be called after createApp().
64
- */
65
- declare function createContentQueryClient(entity: Entity): Promise<ContentQueryClient>;
66
-
67
- export { ContentQueryClient, type ContentQueryClientConfig, createContentQueryClient };
@@ -1,99 +0,0 @@
1
- import { FieldConfig, InferEntityDTO } from '@murumets-ee/entity';
2
-
3
- /**
4
- * Content package types
5
- */
6
-
7
- /**
8
- * A block definition — describes a reusable content block's data shape.
9
- *
10
- * @typeParam F - The literal field map, inferred from the call site.
11
- */
12
- interface BlockDefinition<F extends Record<string, FieldConfig> = Record<string, FieldConfig>> {
13
- slug: string;
14
- label: string;
15
- fields: F;
16
- }
17
- /**
18
- * Infer the data shape of a single block definition.
19
- * Produces `{ _block: 'hero'; _id: string; heading: string; ... }`
20
- */
21
- type InferBlockData<B extends BlockDefinition> = B extends BlockDefinition<infer F> ? {
22
- _block: B['slug'];
23
- _id: string;
24
- } & Omit<InferEntityDTO<F>, 'id'> : never;
25
- /**
26
- * Infer a discriminated union from a tuple of block definitions.
27
- *
28
- * @example
29
- * type Layout = InferBlocksUnion<typeof [HeroBlock, RichTextBlock]>
30
- * // = { _block: 'hero'; ... } | { _block: 'richtext'; ... }
31
- */
32
- type InferBlocksUnion<T extends readonly BlockDefinition[]> = {
33
- [K in keyof T]: T[K] extends BlockDefinition ? InferBlockData<T[K]> : never;
34
- }[number];
35
- interface LocaleConfig {
36
- code: string;
37
- label: string;
38
- }
39
- interface ContentConfig {
40
- locales: LocaleConfig[];
41
- defaultLocale: string;
42
- }
43
- interface VersionableOptions {
44
- /** Maximum versions kept per document. Default: 50 */
45
- maxPerDoc?: number;
46
- /** Enable autosave (single mutable autosave version). Default: false */
47
- autosave?: boolean;
48
- }
49
- interface VersionEntry {
50
- id: string;
51
- entityId: string;
52
- version: number;
53
- locale: string;
54
- data: Record<string, unknown>;
55
- delta: Record<string, unknown> | null;
56
- status: string | null;
57
- createdBy: string | null;
58
- createdByName: string | null;
59
- createdAt: Date | string;
60
- isAutosave: boolean;
61
- }
62
- interface TranslationFieldStatus {
63
- complete: boolean;
64
- total: number;
65
- translated: number;
66
- missing: string[];
67
- }
68
- interface TranslationStatus {
69
- [locale: string]: TranslationFieldStatus;
70
- }
71
- interface TranslationReport {
72
- total: number;
73
- complete: number;
74
- partial: number;
75
- missing: number;
76
- }
77
- interface LocalePublishStatus {
78
- locale: string;
79
- status: 'draft' | 'published';
80
- publishedAt: Date | string | null;
81
- }
82
- interface DraftEntry {
83
- id: string;
84
- entityId: string;
85
- locale: string;
86
- data: Record<string, unknown>;
87
- createdBy: string;
88
- createdByName: string | null;
89
- createdAt: Date | string;
90
- updatedAt: Date | string;
91
- }
92
- interface LockInfo {
93
- lockedBy: string;
94
- lockedByName: string | null;
95
- lockedAt: Date | string;
96
- expiresAt: Date | string;
97
- }
98
-
99
- export type { BlockDefinition as B, ContentConfig as C, DraftEntry as D, InferBlockData as I, LocalePublishStatus as L, TranslationStatus as T, VersionEntry as V, TranslationReport as a, VersionableOptions as b, InferBlocksUnion as c, LocaleConfig as d, LockInfo as e, TranslationFieldStatus as f };
@@ -1,41 +0,0 @@
1
- /**
2
- * Diff result types for version comparison.
3
- */
4
- /** A segment within a word-level text diff. */
5
- interface DiffSegment {
6
- type: 'equal' | 'add' | 'remove';
7
- value: string;
8
- }
9
- /** Diff result for a single scalar field. */
10
- interface FieldDiff {
11
- field: string;
12
- type: 'text' | 'number' | 'boolean' | 'date' | 'select' | 'media' | 'richtext' | 'json' | 'blocks' | 'unknown';
13
- from: unknown;
14
- to: unknown;
15
- /** Word-level diff segments (present for text/richtext/slug fields). */
16
- segments?: DiffSegment[];
17
- /** Block-level structural diff (present for blocks fields). */
18
- blockDiffs?: BlockDiffEntry[];
19
- }
20
- /** Status of a single block within a structural diff. */
21
- type BlockDiffStatus = 'added' | 'removed' | 'moved' | 'changed' | 'unchanged';
22
- /** Diff result for a single block within a blocks field. */
23
- interface BlockDiffEntry {
24
- blockId: string;
25
- blockType: string;
26
- status: BlockDiffStatus;
27
- fromIndex?: number;
28
- toIndex?: number;
29
- /** Per-prop diffs for changed blocks. */
30
- propDiffs?: PropDiff[];
31
- }
32
- /** Diff for a single prop within a changed block. */
33
- interface PropDiff {
34
- field: string;
35
- from: unknown;
36
- to: unknown;
37
- /** Word-level segments for string props. */
38
- segments?: DiffSegment[];
39
- }
40
-
41
- export type { BlockDiffEntry as B, DiffSegment as D, FieldDiff as F, PropDiff as P, BlockDiffStatus as a };