@rizom/brain 0.2.0-alpha.62 → 0.2.0-alpha.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,71 @@
1
1
  import { z } from 'zod';
2
2
 
3
+ /**
4
+ * Context passed to all DataSource operations
5
+ * Contains internal state that should not be mixed with user query parameters
6
+ */
7
+ interface BaseDataSourceContext {
8
+ /**
9
+ * Whether to filter to only published/complete content
10
+ * Set by site-builder: true for production, false for preview
11
+ */
12
+ publishedOnly?: boolean;
13
+ /**
14
+ * Scoped entity service that auto-applies publishedOnly filter
15
+ * Datasources should use this instead of their injected entityService
16
+ * to ensure consistent filtering behavior across environments
17
+ */
18
+ entityService: EntityService;
19
+ }
20
+ /**
21
+ * DataSource Interface
22
+ *
23
+ * Provides data for templates through fetch, generate, or transform operations.
24
+ * DataSources are registered in the DataSourceRegistry and referenced by templates
25
+ * via their dataSourceId property.
26
+ */
27
+ interface DataSource {
28
+ /**
29
+ * Unique identifier for this data source
30
+ */
31
+ id: string;
32
+ /**
33
+ * Human-readable name for this data source
34
+ */
35
+ name: string;
36
+ /**
37
+ * Optional description of what this data source provides
38
+ */
39
+ description?: string;
40
+ /**
41
+ * Optional: Fetch existing data
42
+ * Used by data sources that aggregate or retrieve data (e.g., dashboard stats, API data)
43
+ * DataSources validate output using the provided schema
44
+ * @param query - Query parameters for fetching data
45
+ * @param outputSchema - Schema for validating output data
46
+ * @param context - Context with environment
47
+ */
48
+ fetch?: <T>(query: unknown, outputSchema: z.ZodSchema<T>, context: BaseDataSourceContext) => Promise<T>;
49
+ /**
50
+ * Optional: Generate new content
51
+ * Used by data sources that create content (e.g., AI-generated content, reports)
52
+ */
53
+ generate?: <T>(request: unknown, schema: z.ZodSchema<T>) => Promise<T>;
54
+ /**
55
+ * Optional: Transform content between formats
56
+ * Used by data sources that convert content (e.g., markdown to HTML, data formatting)
57
+ */
58
+ transform?: <T>(content: unknown, format: string, schema: z.ZodSchema<T>) => Promise<T>;
59
+ }
60
+ /**
61
+ * DataSource capabilities for discovery and validation
62
+ */
63
+ interface DataSourceCapabilities {
64
+ canFetch: boolean;
65
+ canGenerate: boolean;
66
+ canTransform: boolean;
67
+ }
68
+
3
69
  /**
4
70
  * Entity type for unstructured notes (the "base" entity type).
5
71
  * Used as a sentinel for the default catch-all markdown file shape —
@@ -227,6 +293,9 @@ interface EntityTypeConfig {
227
293
  /** Whether to generate embeddings for this entity type (default: true).
228
294
  * Set to false for entity types with non-textual content (e.g., images). */
229
295
  embeddable?: boolean;
296
+ /** Whether this entity type may be used as source material for derived projections (default: true).
297
+ * Set to false for projection outputs that would create feedback loops. */
298
+ projectionSource?: boolean;
230
299
  }
231
300
  /**
232
301
  * Core entity service interface for read-only operations
@@ -288,12 +357,11 @@ interface ICoreEntityService {
288
357
  entityType: string;
289
358
  count: number;
290
359
  }>>;
360
+ /** Get configuration for a specific entity type */
361
+ getEntityTypeConfig(type: string): EntityTypeConfig;
291
362
  /** Get weight map for all registered entity types with non-default weights */
292
363
  getWeightMap(): Record<string, number>;
293
364
  }
294
- /**
295
- * Entity service interface for managing brain entities
296
- */
297
365
  interface EntityService extends ICoreEntityService {
298
366
  createEntity<T extends BaseEntity>(request: CreateEntityRequest<T>): Promise<EntityMutationResult>;
299
367
  createEntityFromMarkdown(request: CreateEntityFromMarkdownRequest): Promise<EntityMutationResult>;
@@ -428,72 +496,6 @@ declare function parseMarkdownWithFrontmatter<T>(markdown: string, schema: z.Zod
428
496
  */
429
497
  declare function generateFrontmatter(metadata: Record<string, unknown>): string;
430
498
 
431
- /**
432
- * Context passed to all DataSource operations
433
- * Contains internal state that should not be mixed with user query parameters
434
- */
435
- interface BaseDataSourceContext {
436
- /**
437
- * Whether to filter to only published/complete content
438
- * Set by site-builder: true for production, false for preview
439
- */
440
- publishedOnly?: boolean;
441
- /**
442
- * Scoped entity service that auto-applies publishedOnly filter
443
- * Datasources should use this instead of their injected entityService
444
- * to ensure consistent filtering behavior across environments
445
- */
446
- entityService: EntityService;
447
- }
448
- /**
449
- * DataSource Interface
450
- *
451
- * Provides data for templates through fetch, generate, or transform operations.
452
- * DataSources are registered in the DataSourceRegistry and referenced by templates
453
- * via their dataSourceId property.
454
- */
455
- interface DataSource {
456
- /**
457
- * Unique identifier for this data source
458
- */
459
- id: string;
460
- /**
461
- * Human-readable name for this data source
462
- */
463
- name: string;
464
- /**
465
- * Optional description of what this data source provides
466
- */
467
- description?: string;
468
- /**
469
- * Optional: Fetch existing data
470
- * Used by data sources that aggregate or retrieve data (e.g., dashboard stats, API data)
471
- * DataSources validate output using the provided schema
472
- * @param query - Query parameters for fetching data
473
- * @param outputSchema - Schema for validating output data
474
- * @param context - Context with environment
475
- */
476
- fetch?: <T>(query: unknown, outputSchema: z.ZodSchema<T>, context: BaseDataSourceContext) => Promise<T>;
477
- /**
478
- * Optional: Generate new content
479
- * Used by data sources that create content (e.g., AI-generated content, reports)
480
- */
481
- generate?: <T>(request: unknown, schema: z.ZodSchema<T>) => Promise<T>;
482
- /**
483
- * Optional: Transform content between formats
484
- * Used by data sources that convert content (e.g., markdown to HTML, data formatting)
485
- */
486
- transform?: <T>(content: unknown, format: string, schema: z.ZodSchema<T>) => Promise<T>;
487
- }
488
- /**
489
- * DataSource capabilities for discovery and validation
490
- */
491
- interface DataSourceCapabilities {
492
- canFetch: boolean;
493
- canGenerate: boolean;
494
- canTransform: boolean;
495
- }
496
-
497
499
  /**
498
500
  * Schema for pagination information
499
501
  * Used by datasources that return paginated lists
package/dist/entities.js CHANGED
@@ -166,7 +166,7 @@ Please report this to https://github.com/markedjs/marked.`,$){let X="<p>An error
166
166
  `}format($){try{let J=[`# ${this.config.title}`,""];for(let G of this.config.mappings)this.formatField($,G,J,2);return J.join(`
167
167
  `)}catch{throw Error("Failed to format structured content")}}parse($){try{let J=this.processor.parse($),G=this.extractSections(J,2),X=this.buildDataFromSections(G,this.config.mappings);return this.schema.parse(X)}catch{throw Error("Failed to parse structured content")}}formatField($,J,G,X){let q="#".repeat(X)+" "+J.label,Y=this.getValueByPath($,J.key);if(J.type==="custom"&&J.formatter){if(Y!==void 0&&Y!==null){G.push(q,"");let V=J.formatter(Y);if(V)G.push(V,"")}return}switch(J.type){case"string":case"number":G.push(q,String(Y??""),"");break;case"object":if(G.push(q),J.children&&Y)for(let V of J.children)this.formatField(Y,V,G,X+1);break;case"array":if(G.push(q,""),Array.isArray(Y))if(J.itemType==="object"&&J.itemMappings)Y.forEach((V,W)=>{if(G.push(`${"#".repeat(X+1)} ${J.label.slice(0,-1)} ${W+1}`),G.push(""),J.itemMappings)for(let H of J.itemMappings)this.formatField(V,H,G,X+2)});else{for(let V of Y){let W=this.defaultArrayItemFormat(V);G.push(`- ${W}`)}G.push("")}break}}getValueByPath($,J){let G=J.split("."),X=$;for(let q of G)if(X&&typeof X==="object"&&q in X)X=X[q];else return;return X}defaultArrayItemFormat($){if(typeof $==="string"||typeof $==="number")return String($);return JSON.stringify($)}extractSections($,J){let G=new Map,X=null,q=[];for(let Y of $.children)if(Y.type==="heading"&&Y.depth===J){if(X)G.set(X.toLowerCase(),q);X=this.getHeadingText(Y),q=[]}else if(X)q.push(Y);if(X)G.set(X.toLowerCase(),q);return G}extractSubsections($,J){let G=new Map,X=null,q=[];for(let Y of $)if(Y.type==="heading"&&Y.depth===J){if(X)G.set(X.toLowerCase(),q);X=this.getHeadingText(Y),q=[]}else if(X)q.push(Y);if(X)G.set(X.toLowerCase(),q);return G}textNodeSchema=Z.object({type:Z.literal("text"),value:Z.string()});extractTextValue($){let J=this.textNodeSchema.safeParse($);return J.success?J.data.value:""}getHeadingText($){return $.children.filter((G)=>G.type==="text").map((G)=>this.extractTextValue(G)).join("")}buildDataFromSections($,J,G=2){let X={};for(let q of J){let Y=$.get(q.label.toLowerCase());if(q.type==="custom"&&q.parser&&Y){let V=this.getTextFromSection(Y),W=q.parser(V);this.setValueByPath(X,q.key,W)}else if(q.type==="object"&&q.children&&Y){let V=this.extractSubsections(Y,G+1),W=this.buildDataFromSections(V,q.children,G+1);this.setValueByPath(X,q.key,W)}else if(q.type==="array"&&Y)if(q.itemType==="object"&&q.itemMappings){let V=this.extractObjectArrayItems(Y,G+1,q.itemMappings);this.setValueByPath(X,q.key,V)}else{let V=this.extractSimpleArrayItems(Y);this.setValueByPath(X,q.key,V)}else if(Y){let V=this.getTextFromSection(Y),W=q.type==="number"?Number(V):V;this.setValueByPath(X,q.key,W)}}return X}setValueByPath($,J,G){let X=J.split("."),q=$;for(let V=0;V<X.length-1;V++){let W=X[V];if(!W)continue;if(!(W in q))q[W]={};q=q[W]}let Y=X[X.length-1];if(Y)q[Y]=G}getTextFromSection($){let J=[];for(let G of $)if(G.type==="paragraph"){let X=this.extractTextFromParagraph(G);if(X)J.push(X)}else if(G.type==="list"){let X=G;for(let q of X.children){let Y=this.extractTextFromListItem(q);if(Y)J.push(`- ${Y}`)}}return J.join(`
168
168
  `)}extractTextFromParagraph($){return this.extractInlineText($.children).trim()}extractInlineText($){let J=[];for(let G of $)if(G.type==="text")J.push(this.extractTextValue(G));else if(G.type==="emphasis"){let X=this.extractInlineText(G.children);if(X)J.push(`*${X}*`)}else if(G.type==="strong"){let X=this.extractInlineText(G.children);if(X)J.push(`**${X}**`)}return J.join("")}extractSimpleArrayItems($){let J=[];for(let G of $)if(G.type==="list"){let X=G;for(let q of X.children){let Y=this.extractTextFromListItem(q);if(Y)J.push(Y)}}return J}extractObjectArrayItems($,J,G){let X=[],q=[],Y=!1;for(let V of $)if(V.type==="heading"&&V.depth===J){if(Y&&q.length>0){let W=this.extractSubsections(q,J+1),H=this.buildDataFromSections(W,G,J+1);X.push(H)}q=[],Y=!0}else if(Y)q.push(V);if(Y&&q.length>0){let V=this.extractSubsections(q,J+1),W=this.buildDataFromSections(V,G,J+1);X.push(W)}return X}extractTextFromListItem($){let J=[];for(let G of $.children)if(G.type==="paragraph"){let X=this.extractTextFromParagraph(G);if(X)J.push(X)}return J.join(`
169
- `)}}var IS=Z.object({slug:Z.string(),title:Z.string(),type:Z.string(),entityId:Z.string(),contentHash:Z.string()});var NF=Z.object({success:Z.boolean(),entityId:Z.string().optional(),error:Z.string().optional()});var yC=Z.object({id:Z.string().min(1,"Entity ID is required"),entityType:Z.string().min(1,"Entity type is required"),contentHash:Z.string().min(1,"Content hash is required"),operation:Z.enum(["create","update"])});var pC=Z.object({limit:Z.number().int().positive().optional().default(20),offset:Z.number().int().min(0).optional().default(0),types:Z.array(Z.string()).optional().default([]),excludeTypes:Z.array(Z.string()).optional().default([]),weight:Z.record(Z.string(),Z.number()).optional()});var PF=Z.object({field:Z.string(),direction:Z.enum(["asc","desc"]),nullsFirst:Z.boolean().optional()}),tC=Z.object({limit:Z.number().int().positive().optional(),offset:Z.number().int().min(0).optional().default(0),sortFields:Z.array(PF).optional(),filter:Z.object({metadata:Z.record(Z.string(),Z.unknown()).optional()}).optional(),publishedOnly:Z.boolean().optional()});var H6=o2(n6(),1);function U6($,J){if(Object.keys(J).length===0)return $;let G=Object.fromEntries(Object.entries(J).filter(([,X])=>X!==void 0));return H6.default.stringify($,G)}function z8($){if($ instanceof Date)return $.toISOString();if(Array.isArray($))return $.map(z8);if($!==null&&typeof $==="object"){let J={};for(let[G,X]of Object.entries($))J[G]=z8(X);return J}return $}function p0($,J){let{content:G,data:X}=H6.default($),q=z8(X);return{content:G.trim(),metadata:J.parse(q)}}function Q6($){if(Object.keys($).length===0)return"";let G=H6.default.stringify("",$).match(/^---\n[\s\S]*?\n---/);return G?G[0]:""}var vF={generateBodyTemplate:()=>""};class c2{entityType;schema;frontmatterSchema;isSingleton;hasBody;supportsCoverImage;fmSchema;bodyFormatter;constructor($){if(this.entityType=$.entityType,this.schema=$.schema,this.frontmatterSchema=$.frontmatterSchema,this.fmSchema=$.frontmatterSchema,this.bodyFormatter=$.bodyFormatter??vF,$.isSingleton!==void 0)this.isSingleton=$.isSingleton;if($.hasBody!==void 0)this.hasBody=$.hasBody;if($.supportsCoverImage!==void 0)this.supportsCoverImage=$.supportsCoverImage}toMarkdown($){let J=this.renderBody($),X={...this.readExistingFrontmatter($.content)},q=Object.keys(this.frontmatterSchema.shape);for(let[Y,V]of Object.entries($.metadata))if(q.includes(Y))X[Y]=V;return this.buildMarkdown(J,X)}renderBody($){return this.extractBody($.content)}readExistingFrontmatter($){try{return p0($,Z.record(Z.unknown())).metadata}catch{return{}}}extractMetadata($){return $.metadata}parseFrontMatter($,J){return p0($,J).metadata}getBodyTemplate(){return this.bodyFormatter.generateBodyTemplate()}generateFrontMatter($){let J=$.metadata;return Q6(J)}extractBody($){try{return p0($,Z.record(Z.unknown())).content}catch{return $}}parseFrontmatter($){return p0($,this.fmSchema).metadata}buildMarkdown($,J){return U6($,J)}}var kX="base",K8=Z.object({id:Z.string(),entityType:Z.string(),content:Z.string(),created:Z.string().datetime(),updated:Z.string().datetime(),metadata:Z.record(Z.string(),Z.unknown()),contentHash:Z.string()});var yX=Z.object({currentPage:Z.number(),totalPages:Z.number(),totalItems:Z.number(),pageSize:Z.number(),hasNextPage:Z.boolean(),hasPrevPage:Z.boolean()});function fX($,J,G){let X=Math.max(1,Math.ceil($/G));return{currentPage:J,totalPages:X,totalItems:$,pageSize:G,hasNextPage:J<X,hasPrevPage:J>1}}function mX($,J){let{page:G,limit:X,pageSize:q}=J;if(G!==void 0){let Y=G,V=q??X??$.length,W=$.length,H=Math.ceil(W/V),U=(Y-1)*V,Q=U+V;return{items:$.slice(U,Q),pagination:{currentPage:Y,totalPages:H,totalItems:W,pageSize:V,hasNextPage:Y<H,hasPrevPage:Y>1}}}if(X!==void 0)return{items:$.slice(0,X),pagination:null};return{items:$,pagination:null}}export{p0 as parseMarkdownWithFrontmatter,yX as paginationInfoSchema,mX as paginateItems,U6 as generateMarkdownWithFrontmatter,Q6 as generateFrontmatter,fX as buildPaginationInfo,K8 as baseEntitySchema,c2 as BaseEntityAdapter,kX as BASE_ENTITY_TYPE};
169
+ `)}}var IS=Z.object({slug:Z.string(),title:Z.string(),type:Z.string(),entityId:Z.string(),contentHash:Z.string()});var NF=Z.object({success:Z.boolean(),entityId:Z.string().optional(),error:Z.string().optional()});var fC=Z.object({id:Z.string().min(1,"Entity ID is required"),entityType:Z.string().min(1,"Entity type is required"),contentHash:Z.string().min(1,"Content hash is required"),operation:Z.enum(["create","update"])});var lC=Z.object({limit:Z.number().int().positive().optional().default(20),offset:Z.number().int().min(0).optional().default(0),types:Z.array(Z.string()).optional().default([]),excludeTypes:Z.array(Z.string()).optional().default([]),weight:Z.record(Z.string(),Z.number()).optional()});var PF=Z.object({field:Z.string(),direction:Z.enum(["asc","desc"]),nullsFirst:Z.boolean().optional()}),eC=Z.object({limit:Z.number().int().positive().optional(),offset:Z.number().int().min(0).optional().default(0),sortFields:Z.array(PF).optional(),filter:Z.object({metadata:Z.record(Z.string(),Z.unknown()).optional()}).optional(),publishedOnly:Z.boolean().optional()});var H6=o2(n6(),1);function U6($,J){if(Object.keys(J).length===0)return $;let G=Object.fromEntries(Object.entries(J).filter(([,X])=>X!==void 0));return H6.default.stringify($,G)}function z8($){if($ instanceof Date)return $.toISOString();if(Array.isArray($))return $.map(z8);if($!==null&&typeof $==="object"){let J={};for(let[G,X]of Object.entries($))J[G]=z8(X);return J}return $}function p0($,J){let{content:G,data:X}=H6.default($),q=z8(X);return{content:G.trim(),metadata:J.parse(q)}}function Q6($){if(Object.keys($).length===0)return"";let G=H6.default.stringify("",$).match(/^---\n[\s\S]*?\n---/);return G?G[0]:""}var vF={generateBodyTemplate:()=>""};class c2{entityType;schema;frontmatterSchema;isSingleton;hasBody;supportsCoverImage;fmSchema;bodyFormatter;constructor($){if(this.entityType=$.entityType,this.schema=$.schema,this.frontmatterSchema=$.frontmatterSchema,this.fmSchema=$.frontmatterSchema,this.bodyFormatter=$.bodyFormatter??vF,$.isSingleton!==void 0)this.isSingleton=$.isSingleton;if($.hasBody!==void 0)this.hasBody=$.hasBody;if($.supportsCoverImage!==void 0)this.supportsCoverImage=$.supportsCoverImage}toMarkdown($){let J=this.renderBody($),X={...this.readExistingFrontmatter($.content)},q=Object.keys(this.frontmatterSchema.shape);for(let[Y,V]of Object.entries($.metadata))if(q.includes(Y))X[Y]=V;return this.buildMarkdown(J,X)}renderBody($){return this.extractBody($.content)}readExistingFrontmatter($){try{return p0($,Z.record(Z.unknown())).metadata}catch{return{}}}extractMetadata($){return $.metadata}parseFrontMatter($,J){return p0($,J).metadata}getBodyTemplate(){return this.bodyFormatter.generateBodyTemplate()}generateFrontMatter($){let J=$.metadata;return Q6(J)}extractBody($){try{return p0($,Z.record(Z.unknown())).content}catch{return $}}parseFrontmatter($){return p0($,this.fmSchema).metadata}buildMarkdown($,J){return U6($,J)}}var kX="base",K8=Z.object({id:Z.string(),entityType:Z.string(),content:Z.string(),created:Z.string().datetime(),updated:Z.string().datetime(),metadata:Z.record(Z.string(),Z.unknown()),contentHash:Z.string()});var yX=Z.object({currentPage:Z.number(),totalPages:Z.number(),totalItems:Z.number(),pageSize:Z.number(),hasNextPage:Z.boolean(),hasPrevPage:Z.boolean()});function fX($,J,G){let X=Math.max(1,Math.ceil($/G));return{currentPage:J,totalPages:X,totalItems:$,pageSize:G,hasNextPage:J<X,hasPrevPage:J>1}}function mX($,J){let{page:G,limit:X,pageSize:q}=J;if(G!==void 0){let Y=G,V=q??X??$.length,W=$.length,H=Math.ceil(W/V),U=(Y-1)*V,Q=U+V;return{items:$.slice(U,Q),pagination:{currentPage:Y,totalPages:H,totalItems:W,pageSize:V,hasNextPage:Y<H,hasPrevPage:Y>1}}}if(X!==void 0)return{items:$.slice(0,X),pagination:null};return{items:$,pagination:null}}export{p0 as parseMarkdownWithFrontmatter,yX as paginationInfoSchema,mX as paginateItems,U6 as generateMarkdownWithFrontmatter,Q6 as generateFrontmatter,fX as buildPaginationInfo,K8 as baseEntitySchema,c2 as BaseEntityAdapter,kX as BASE_ENTITY_TYPE};
170
170
 
171
- //# debugId=8AB32B1F21E0286164756E2164756E21
171
+ //# debugId=DDF982E4E60BB5C464756E2164756E21
172
172
  //# sourceMappingURL=entities.js.map