jsonldjs 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,269 @@
1
+ "use strict";
2
+ /**
3
+ * Utility functions for JSON-LD builder
4
+ *
5
+ * Provides configuration merging, validation, and transformation utilities
6
+ * for the JSON-LD builder system.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.mergeConfigs = mergeConfigs;
10
+ exports.mergeFilterOptions = mergeFilterOptions;
11
+ exports.convertPropertyFiltersByIds = convertPropertyFiltersByIds;
12
+ exports.convertPropertyFiltersByTypes = convertPropertyFiltersByTypes;
13
+ exports.buildPropertyFilterConfig = buildPropertyFilterConfig;
14
+ exports.validateConfig = validateConfig;
15
+ exports.applyPopulateConfig = applyPopulateConfig;
16
+ exports.validateRuntimeConfig = validateRuntimeConfig;
17
+ exports.entityHasType = entityHasType;
18
+ exports.entityHasAnyType = entityHasAnyType;
19
+ exports.getEntityTypes = getEntityTypes;
20
+ exports.filterJsonLdGraph = filterJsonLdGraph;
21
+ /**
22
+ * Merge two configurations, with the second taking precedence
23
+ */
24
+ function mergeConfigs(base, override) {
25
+ return {
26
+ // Base graph: override takes precedence
27
+ baseGraph: override.baseGraph ?? base.baseGraph,
28
+ // Filters: merge filter options
29
+ filters: mergeFilterOptions(base.filters, override.filters),
30
+ // Additional entities: combine arrays
31
+ additionalEntities: combineArrays(base.additionalEntities, override.additionalEntities),
32
+ // Pipes: combine arrays
33
+ pipes: combineArrays(base.pipes, override.pipes),
34
+ // Populate config: override takes precedence
35
+ populateConfig: override.populateConfig ?? base.populateConfig,
36
+ };
37
+ }
38
+ /**
39
+ * Merge filter options, merging arrays and using override for single values
40
+ */
41
+ function mergeFilterOptions(base, override) {
42
+ if (!base && !override)
43
+ return undefined;
44
+ if (!base)
45
+ return override;
46
+ if (!override)
47
+ return base;
48
+ return {
49
+ // Merge arrays instead of replacing
50
+ includeTypes: combineArrays(base.includeTypes, override.includeTypes),
51
+ excludeTypes: combineArrays(base.excludeTypes, override.excludeTypes),
52
+ includeIds: combineArrays(base.includeIds, override.includeIds),
53
+ excludeIds: combineArrays(base.excludeIds, override.excludeIds),
54
+ requiredProperties: combineArrays(base.requiredProperties, override.requiredProperties),
55
+ excludeEntitiesWithProperties: combineArrays(base.excludeEntitiesWithProperties, override.excludeEntitiesWithProperties),
56
+ subgraphRoots: combineArrays(base.subgraphRoots, override.subgraphRoots),
57
+ propertyFilters: combinePropertyFilters(base.propertyFilters, override.propertyFilters),
58
+ propertyFiltersByIds: combineArrays(base.propertyFiltersByIds, override.propertyFiltersByIds),
59
+ propertyFiltersByTypes: combineArrays(base.propertyFiltersByTypes, override.propertyFiltersByTypes),
60
+ // Single values - override takes precedence
61
+ customFilter: override.customFilter ?? base.customFilter,
62
+ maxEntities: override.maxEntities ?? base.maxEntities,
63
+ };
64
+ }
65
+ /**
66
+ * Combine property filter configurations
67
+ */
68
+ function combinePropertyFilters(base, override) {
69
+ if (!base && !override)
70
+ return undefined;
71
+ if (!base)
72
+ return override;
73
+ if (!override)
74
+ return base;
75
+ return [...base, ...override];
76
+ }
77
+ /**
78
+ * Combine arrays, handling undefined values
79
+ */
80
+ function combineArrays(base, override) {
81
+ if (!base && !override)
82
+ return undefined;
83
+ if (!base)
84
+ return override;
85
+ if (!override)
86
+ return base;
87
+ return [...base, ...override];
88
+ }
89
+ /**
90
+ * Convert property filter by ID rules to PropertyFilterConfig
91
+ */
92
+ function convertPropertyFiltersByIds(rules) {
93
+ return rules.flatMap((rule) => rule.entityIds.map((entityId) => ({
94
+ selector: { '@id': entityId },
95
+ include: rule.include,
96
+ exclude: rule.exclude,
97
+ })));
98
+ }
99
+ /**
100
+ * Convert property filter by type rules to PropertyFilterConfig
101
+ */
102
+ function convertPropertyFiltersByTypes(rules) {
103
+ return rules.flatMap((rule) => rule.entityTypes.map((entityType) => ({
104
+ selector: { '@type': entityType },
105
+ include: rule.include,
106
+ exclude: rule.exclude,
107
+ })));
108
+ }
109
+ /**
110
+ * Build complete property filter configuration from all sources
111
+ */
112
+ function buildPropertyFilterConfig(config) {
113
+ const filters = [];
114
+ // Add base property filters
115
+ if (config.filters?.propertyFilters) {
116
+ filters.push(...config.filters.propertyFilters);
117
+ }
118
+ // Add property filters by IDs
119
+ if (config.filters?.propertyFiltersByIds) {
120
+ filters.push(...convertPropertyFiltersByIds(config.filters.propertyFiltersByIds));
121
+ }
122
+ // Add property filters by types
123
+ if (config.filters?.propertyFiltersByTypes) {
124
+ filters.push(...convertPropertyFiltersByTypes(config.filters.propertyFiltersByTypes));
125
+ }
126
+ return filters.length > 0 ? filters : undefined;
127
+ }
128
+ /**
129
+ * Validate configuration for common issues
130
+ */
131
+ function validateConfig(config) {
132
+ const errors = [];
133
+ // Check for conflicting include/exclude types
134
+ if (config.filters?.includeTypes && config.filters?.excludeTypes) {
135
+ const overlap = config.filters.includeTypes.filter((type) => config.filters.excludeTypes.includes(type));
136
+ if (overlap.length > 0) {
137
+ errors.push(`Conflicting include/exclude types: ${overlap.join(', ')}`);
138
+ }
139
+ }
140
+ // Check for conflicting include/exclude IDs
141
+ if (config.filters?.includeIds && config.filters?.excludeIds) {
142
+ const overlap = config.filters.includeIds.filter((id) => config.filters.excludeIds.includes(id));
143
+ if (overlap.length > 0) {
144
+ errors.push(`Conflicting include/exclude IDs: ${overlap.join(', ')}`);
145
+ }
146
+ }
147
+ // Check for invalid maxEntities
148
+ if (config.filters?.maxEntities !== undefined && config.filters.maxEntities < 1) {
149
+ errors.push('maxEntities must be greater than 0');
150
+ }
151
+ return errors;
152
+ }
153
+ /**
154
+ * Apply populate configuration to entities in the graph
155
+ */
156
+ function applyPopulateConfig(graph, populateConfig) {
157
+ return graph.map((entity) => {
158
+ const entityId = entity['@id'];
159
+ const populateRules = populateConfig[entityId];
160
+ if (!populateRules || populateRules.length === 0) {
161
+ return entity;
162
+ }
163
+ // Create a copy of the entity to avoid mutation
164
+ const populatedEntity = { ...entity };
165
+ // Apply each populate rule
166
+ for (const rule of populateRules) {
167
+ populatedEntity[rule.property] = rule.entities;
168
+ }
169
+ return populatedEntity;
170
+ });
171
+ }
172
+ /**
173
+ * Validate runtime configuration for critical errors only
174
+ * This is more lenient than the general validateConfig to handle runtime overrides
175
+ */
176
+ function validateRuntimeConfig(config) {
177
+ const errors = [];
178
+ // Check for baseGraph requirement
179
+ if (!config.baseGraph) {
180
+ errors.push('baseGraph is required');
181
+ }
182
+ else if (!Array.isArray(config.baseGraph)) {
183
+ errors.push('baseGraph must be an array');
184
+ }
185
+ // Only check for critical errors that would break processing
186
+ if (config.filters?.maxEntities !== undefined && config.filters.maxEntities < 1) {
187
+ errors.push('maxEntities must be greater than 0');
188
+ }
189
+ return errors;
190
+ }
191
+ /**
192
+ * Type guard to check if an entity matches a type
193
+ */
194
+ function entityHasType(entity, type) {
195
+ const entityType = entity['@type'];
196
+ if (!entityType)
197
+ return false;
198
+ if (Array.isArray(entityType)) {
199
+ return entityType.includes(type);
200
+ }
201
+ return entityType === type;
202
+ }
203
+ /**
204
+ * Type guard to check if an entity has any of the specified types
205
+ */
206
+ function entityHasAnyType(entity, types) {
207
+ return types.some((type) => entityHasType(entity, type));
208
+ }
209
+ /**
210
+ * Get all types from an entity as an array
211
+ */
212
+ function getEntityTypes(entity) {
213
+ const entityType = entity['@type'];
214
+ if (!entityType)
215
+ return [];
216
+ return Array.isArray(entityType) ? entityType : [entityType];
217
+ }
218
+ /**
219
+ * Apply filters to a JSON-LD graph (copied from head-manager/filters.ts for self-containment)
220
+ */
221
+ function filterJsonLdGraph(graph, options) {
222
+ let filtered = [...graph];
223
+ // Apply type inclusion filter
224
+ if (options.includeTypes && options.includeTypes.length > 0) {
225
+ filtered = filtered.filter((entity) => {
226
+ const type = entity['@type'];
227
+ if (!type)
228
+ return false;
229
+ const types = Array.isArray(type) ? type : [type];
230
+ return types.some((t) => options.includeTypes.includes(t));
231
+ });
232
+ }
233
+ // Apply type exclusion filter
234
+ if (options.excludeTypes && options.excludeTypes.length > 0) {
235
+ filtered = filtered.filter((entity) => {
236
+ const type = entity['@type'];
237
+ if (!type)
238
+ return true;
239
+ const types = Array.isArray(type) ? type : [type];
240
+ return !types.some((t) => options.excludeTypes.includes(t));
241
+ });
242
+ }
243
+ // Apply ID inclusion filter
244
+ if (options.includeIds && options.includeIds.length > 0) {
245
+ filtered = filtered.filter((entity) => entity['@id'] && options.includeIds.includes(entity['@id']));
246
+ }
247
+ // Apply ID exclusion filter
248
+ if (options.excludeIds && options.excludeIds.length > 0) {
249
+ filtered = filtered.filter((entity) => !entity['@id'] || !options.excludeIds.includes(entity['@id']));
250
+ }
251
+ // Apply required properties filter
252
+ if (options.requiredProperties && options.requiredProperties.length > 0) {
253
+ filtered = filtered.filter((entity) => options.requiredProperties.every((prop) => prop in entity));
254
+ }
255
+ // Apply excluded properties filter (handle both old and new property names)
256
+ const excludeProps = options.excludeEntitiesWithProperties || options.excludeProperties;
257
+ if (excludeProps && excludeProps.length > 0) {
258
+ filtered = filtered.filter((entity) => !excludeProps.some((prop) => prop in entity));
259
+ }
260
+ // Apply custom filter
261
+ if (options.customFilter) {
262
+ filtered = filtered.filter(options.customFilter);
263
+ }
264
+ // Apply max entities limit
265
+ if (options.maxEntities && options.maxEntities > 0) {
266
+ filtered = filtered.slice(0, options.maxEntities);
267
+ }
268
+ return filtered;
269
+ }
package/builder.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * JSON-LD Builder with fluent interface
3
+ *
4
+ * Provides a mutable builder that applies configurations and processes graphs.
5
+ * Supports runtime overrides and maintains the complex filtering logic from
6
+ * the current head-manager system.
7
+ */
8
+ import { JsonLdConfigBuilder } from './config';
9
+ import { type JsonLdGraph } from './jsonld-utils';
10
+ import type { BuildOptions, JsonLdConfig } from './types';
11
+ /**
12
+ * Mutable builder class that extends config builder with automatic method delegation
13
+ */
14
+ export declare class JsonLdBuilder extends JsonLdConfigBuilder {
15
+ private currentGraph?;
16
+ constructor(initialConfig?: JsonLdConfig);
17
+ /**
18
+ * Override the config builder's method creation to return JsonLdBuilder instances
19
+ */
20
+ protected createInstance(config: JsonLdConfig): JsonLdBuilder;
21
+ /**
22
+ * Get the current graph state (processes the graph if not already done)
23
+ */
24
+ getCurrentGraph(): JsonLdGraph;
25
+ /**
26
+ * Build the final JSON-LD output
27
+ * @param options - Build configuration options
28
+ * @param options.prettyPrint - Whether to format JSON with indentation (default: true)
29
+ * @param options.contextUrl - The JSON-LD context URL (default: 'https://schema.org')
30
+ * @param options.withScriptTag - Whether to wrap output in a script tag (default: false)
31
+ * @param options.scriptId - Optional ID attribute for the script tag
32
+ * @returns The JSON-LD string, optionally wrapped in a script tag
33
+ */
34
+ build(options?: BuildOptions): string;
35
+ /**
36
+ * Process the graph according to the current configuration
37
+ * This implements the critical filtering logic from the current manager
38
+ */
39
+ private processGraph;
40
+ }
41
+ /**
42
+ * Factory function to create a new builder
43
+ */
44
+ export declare function createJsonLdBuilder(): JsonLdBuilder;
package/builder.js ADDED
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ /**
3
+ * JSON-LD Builder with fluent interface
4
+ *
5
+ * Provides a mutable builder that applies configurations and processes graphs.
6
+ * Supports runtime overrides and maintains the complex filtering logic from
7
+ * the current head-manager system.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.JsonLdBuilder = void 0;
11
+ exports.createJsonLdBuilder = createJsonLdBuilder;
12
+ const config_1 = require("./config");
13
+ const jsonld_utils_1 = require("./jsonld-utils");
14
+ const builder_utils_1 = require("./builder-utils");
15
+ /**
16
+ * Mutable builder class that extends config builder with automatic method delegation
17
+ */
18
+ class JsonLdBuilder extends config_1.JsonLdConfigBuilder {
19
+ constructor(initialConfig = {}) {
20
+ super(initialConfig);
21
+ }
22
+ /**
23
+ * Override the config builder's method creation to return JsonLdBuilder instances
24
+ */
25
+ createInstance(config) {
26
+ return new JsonLdBuilder(config);
27
+ }
28
+ /**
29
+ * Get the current graph state (processes the graph if not already done)
30
+ */
31
+ getCurrentGraph() {
32
+ if (!this.currentGraph) {
33
+ this.currentGraph = this.processGraph();
34
+ }
35
+ return this.currentGraph;
36
+ }
37
+ /**
38
+ * Build the final JSON-LD output
39
+ * @param options - Build configuration options
40
+ * @param options.prettyPrint - Whether to format JSON with indentation (default: true)
41
+ * @param options.contextUrl - The JSON-LD context URL (default: 'https://schema.org')
42
+ * @param options.withScriptTag - Whether to wrap output in a script tag (default: false)
43
+ * @param options.scriptId - Optional ID attribute for the script tag
44
+ * @returns The JSON-LD string, optionally wrapped in a script tag
45
+ */
46
+ build(options = {}) {
47
+ const { prettyPrint = true, contextUrl = 'https://schema.org', withScriptTag = false, scriptId, } = options;
48
+ const graph = this.getCurrentGraph();
49
+ // Create the JSON-LD object
50
+ const jsonLd = {
51
+ '@context': contextUrl,
52
+ '@graph': graph,
53
+ };
54
+ // Stringify with optional pretty printing
55
+ const jsonString = JSON.stringify(jsonLd, null, prettyPrint ? 2 : undefined);
56
+ // Wrap in script tag if requested
57
+ if (withScriptTag) {
58
+ const idAttribute = scriptId ? ` id="${scriptId}"` : '';
59
+ return `<script${idAttribute} type="application/ld+json">${jsonString}</script>`;
60
+ }
61
+ return jsonString;
62
+ }
63
+ /**
64
+ * Process the graph according to the current configuration
65
+ * This implements the critical filtering logic from the current manager
66
+ */
67
+ processGraph() {
68
+ const config = this.getConfig();
69
+ if (!config.baseGraph) {
70
+ throw new Error('No base graph provided. Use baseGraph() or mergeConfig() with a baseGraph.');
71
+ }
72
+ // Validate configuration - only check for critical errors that would break processing
73
+ const errors = (0, builder_utils_1.validateRuntimeConfig)(config);
74
+ if (errors.length > 0) {
75
+ throw new Error(`Configuration validation failed: ${errors.join(', ')}`);
76
+ }
77
+ let graph = [...config.baseGraph];
78
+ const propertyFilters = (0, builder_utils_1.buildPropertyFilterConfig)(config);
79
+ let propertyFiltersApplied = false;
80
+ // Layer 1: Subgraph extraction with property filtering if subgraphRoots are set
81
+ if (config.filters?.subgraphRoots && config.filters.subgraphRoots.length > 0) {
82
+ // Extract subgraph with property filtering during traversal
83
+ graph = (0, jsonld_utils_1.extractSubgraphs)(graph, config.filters.subgraphRoots, propertyFilters);
84
+ propertyFiltersApplied = true; // Property filters were applied during subgraph extraction
85
+ }
86
+ // Layer 2: Regular entity filtering with property filtering if not already applied
87
+ if (config.filters) {
88
+ // Apply property filters first if they haven't been applied yet
89
+ if (!propertyFiltersApplied && propertyFilters) {
90
+ graph = (0, jsonld_utils_1.filterGraphProperties)(graph, propertyFilters);
91
+ propertyFiltersApplied = true;
92
+ }
93
+ // Apply entity-level filters
94
+ graph = (0, builder_utils_1.filterJsonLdGraph)(graph, config.filters);
95
+ }
96
+ // Apply entity population if configured
97
+ if (config.populateConfig) {
98
+ graph = (0, builder_utils_1.applyPopulateConfig)(graph, config.populateConfig);
99
+ }
100
+ // Add additional entities if specified
101
+ if (config.additionalEntities && config.additionalEntities.length > 0) {
102
+ graph = [...graph, ...config.additionalEntities];
103
+ }
104
+ // Apply custom transformation pipes
105
+ if (config.pipes && config.pipes.length > 0) {
106
+ for (const pipe of config.pipes) {
107
+ graph = pipe(graph);
108
+ }
109
+ }
110
+ return graph;
111
+ }
112
+ }
113
+ exports.JsonLdBuilder = JsonLdBuilder;
114
+ /**
115
+ * Factory function to create a new builder
116
+ */
117
+ function createJsonLdBuilder() {
118
+ return new JsonLdBuilder();
119
+ }
package/config.d.ts ADDED
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Immutable configuration builder for JSON-LD processing
3
+ *
4
+ * Provides a fluent interface for building configurations without
5
+ * performing any graph processing. Each method returns a new
6
+ * configuration object for safe reuse and extension.
7
+ */
8
+ import type { IJsonLdConfigBuilder, JsonLdConfig, JsonLdEntity, JsonLdFilter, JsonLdFilterOptions, JsonLdGraph, PipeFunction, PopulateConfig } from './types';
9
+ /**
10
+ * Immutable configuration builder class
11
+ */
12
+ export declare class JsonLdConfigBuilder implements IJsonLdConfigBuilder {
13
+ private config;
14
+ constructor(initialConfig?: JsonLdConfig);
15
+ /**
16
+ * Create a new instance of this class (can be overridden by subclasses)
17
+ */
18
+ protected createInstance(config: JsonLdConfig): JsonLdConfigBuilder;
19
+ /**
20
+ * Set the base graph to process
21
+ */
22
+ baseGraph(graph: JsonLdGraph): this;
23
+ /**
24
+ * Include only entities with these IDs (merges with existing IDs)
25
+ */
26
+ includeIds(ids: string[]): this;
27
+ /**
28
+ * Exclude entities with these IDs (merges with existing IDs)
29
+ */
30
+ excludeIds(ids: string[]): this;
31
+ /**
32
+ * Include only these entity types (merges with existing types)
33
+ */
34
+ includeTypes(types: string[]): this;
35
+ /**
36
+ * Exclude these entity types (merges with existing types)
37
+ */
38
+ excludeTypes(types: string[]): this;
39
+ /**
40
+ * Apply custom filter function
41
+ */
42
+ customFilter(fn: JsonLdFilter): this;
43
+ /**
44
+ * Limit maximum number of entities
45
+ */
46
+ maxEntities(max: number): this;
47
+ /**
48
+ * Include only entities with these properties (merges with existing properties)
49
+ * @param props - Array of property names that entities must have
50
+ * @example
51
+ * ```typescript
52
+ * config.requiredProperties(['name']).requiredProperties(['url'])
53
+ * // Result: entities must have both 'name' and 'url' properties
54
+ * ```
55
+ */
56
+ requiredProperties(props: string[]): this;
57
+ /**
58
+ * Exclude entities with these properties (merges with existing properties)
59
+ */
60
+ excludeEntitiesWithProperties(props: string[]): this;
61
+ /**
62
+ * Extract subgraph starting from these root IDs
63
+ */
64
+ subgraph(rootIds: string[]): this;
65
+ /**
66
+ * Filter properties for specific entity IDs
67
+ */
68
+ filterPropertiesByIds(entityIds: string[], rule: {
69
+ include?: string[];
70
+ exclude?: string[];
71
+ }): this;
72
+ /**
73
+ * Filter properties for specific entity types
74
+ */
75
+ filterPropertiesByTypes(entityTypes: string[], rule: {
76
+ include?: string[];
77
+ exclude?: string[];
78
+ }): this;
79
+ /**
80
+ * Add additional entities
81
+ */
82
+ addEntities(entities: JsonLdEntity[]): this;
83
+ /**
84
+ * Add custom transformation pipe
85
+ */
86
+ pipe(fn: PipeFunction): this;
87
+ /**
88
+ * Configure entity population
89
+ */
90
+ populateEntities(entityIds: string[], populateConfig: PopulateConfig): this;
91
+ /**
92
+ * Clear both includeIds and excludeIds
93
+ * @example
94
+ * ```typescript
95
+ * config.includeIds(['a']).excludeIds(['b']).clearIds().includeIds(['c'])
96
+ * // Result: only includes 'c', previous IDs are cleared
97
+ * ```
98
+ */
99
+ clearIds(): this;
100
+ /**
101
+ * Clear both includeTypes and excludeTypes
102
+ */
103
+ clearTypes(): this;
104
+ /**
105
+ * Clear both requiredProperties and excludeEntitiesWithProperties
106
+ */
107
+ clearPropertyRequirements(): this;
108
+ /**
109
+ * Clear both propertyFiltersByIds and propertyFiltersByTypes
110
+ */
111
+ clearPropertyFilters(): this;
112
+ /**
113
+ * Clear subgraphRoots
114
+ */
115
+ clearSubgraph(): this;
116
+ /**
117
+ * Clear entire configuration except baseGraph
118
+ * @example
119
+ * ```typescript
120
+ * config.baseGraph(graph).includeIds(['a']).clearAll().includeTypes(['Person'])
121
+ * // Result: only baseGraph and includeTypes remain
122
+ * ```
123
+ */
124
+ clearAll(): this;
125
+ /**
126
+ * Merge with another configuration
127
+ * @param config - Configuration to merge with current configuration
128
+ */
129
+ mergeConfig(config: JsonLdConfig): this;
130
+ /**
131
+ * Merge only the filters part of another configuration
132
+ * @param filters - Filter options to merge with current filters
133
+ */
134
+ mergeFilters(filters: JsonLdFilterOptions): this;
135
+ /**
136
+ * Get the current configuration
137
+ */
138
+ getConfig(): JsonLdConfig;
139
+ }
140
+ /**
141
+ * Factory function to create a new configuration builder
142
+ */
143
+ export declare function createJsonLdConfig(): JsonLdConfigBuilder;