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.
package/config.js ADDED
@@ -0,0 +1,344 @@
1
+ "use strict";
2
+ /**
3
+ * Immutable configuration builder for JSON-LD processing
4
+ *
5
+ * Provides a fluent interface for building configurations without
6
+ * performing any graph processing. Each method returns a new
7
+ * configuration object for safe reuse and extension.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.JsonLdConfigBuilder = void 0;
11
+ exports.createJsonLdConfig = createJsonLdConfig;
12
+ const builder_utils_1 = require("./builder-utils");
13
+ /**
14
+ * Immutable configuration builder class
15
+ */
16
+ class JsonLdConfigBuilder {
17
+ constructor(initialConfig = {}) {
18
+ this.config = { ...initialConfig };
19
+ }
20
+ /**
21
+ * Create a new instance of this class (can be overridden by subclasses)
22
+ */
23
+ createInstance(config) {
24
+ return new JsonLdConfigBuilder(config);
25
+ }
26
+ /**
27
+ * Set the base graph to process
28
+ */
29
+ baseGraph(graph) {
30
+ return this.createInstance({
31
+ ...this.config,
32
+ baseGraph: graph,
33
+ });
34
+ }
35
+ /**
36
+ * Include only entities with these IDs (merges with existing IDs)
37
+ */
38
+ includeIds(ids) {
39
+ const existingIds = this.config.filters?.includeIds || [];
40
+ return this.createInstance({
41
+ ...this.config,
42
+ filters: {
43
+ ...this.config.filters,
44
+ includeIds: [...existingIds, ...ids],
45
+ },
46
+ });
47
+ }
48
+ /**
49
+ * Exclude entities with these IDs (merges with existing IDs)
50
+ */
51
+ excludeIds(ids) {
52
+ const existingIds = this.config.filters?.excludeIds || [];
53
+ return this.createInstance({
54
+ ...this.config,
55
+ filters: {
56
+ ...this.config.filters,
57
+ excludeIds: [...existingIds, ...ids],
58
+ },
59
+ });
60
+ }
61
+ /**
62
+ * Include only these entity types (merges with existing types)
63
+ */
64
+ includeTypes(types) {
65
+ const existingTypes = this.config.filters?.includeTypes || [];
66
+ return this.createInstance({
67
+ ...this.config,
68
+ filters: {
69
+ ...this.config.filters,
70
+ includeTypes: [...existingTypes, ...types],
71
+ },
72
+ });
73
+ }
74
+ /**
75
+ * Exclude these entity types (merges with existing types)
76
+ */
77
+ excludeTypes(types) {
78
+ const existingTypes = this.config.filters?.excludeTypes || [];
79
+ return this.createInstance({
80
+ ...this.config,
81
+ filters: {
82
+ ...this.config.filters,
83
+ excludeTypes: [...existingTypes, ...types],
84
+ },
85
+ });
86
+ }
87
+ /**
88
+ * Apply custom filter function
89
+ */
90
+ customFilter(fn) {
91
+ return this.createInstance({
92
+ ...this.config,
93
+ filters: {
94
+ ...this.config.filters,
95
+ customFilter: fn,
96
+ },
97
+ });
98
+ }
99
+ /**
100
+ * Limit maximum number of entities
101
+ */
102
+ maxEntities(max) {
103
+ return this.createInstance({
104
+ ...this.config,
105
+ filters: {
106
+ ...this.config.filters,
107
+ maxEntities: max,
108
+ },
109
+ });
110
+ }
111
+ /**
112
+ * Include only entities with these properties (merges with existing properties)
113
+ * @param props - Array of property names that entities must have
114
+ * @example
115
+ * ```typescript
116
+ * config.requiredProperties(['name']).requiredProperties(['url'])
117
+ * // Result: entities must have both 'name' and 'url' properties
118
+ * ```
119
+ */
120
+ requiredProperties(props) {
121
+ const existingProps = this.config.filters?.requiredProperties || [];
122
+ return this.createInstance({
123
+ ...this.config,
124
+ filters: {
125
+ ...this.config.filters,
126
+ requiredProperties: [...existingProps, ...props],
127
+ },
128
+ });
129
+ }
130
+ /**
131
+ * Exclude entities with these properties (merges with existing properties)
132
+ */
133
+ excludeEntitiesWithProperties(props) {
134
+ const existingProps = this.config.filters?.excludeEntitiesWithProperties || [];
135
+ return this.createInstance({
136
+ ...this.config,
137
+ filters: {
138
+ ...this.config.filters,
139
+ excludeEntitiesWithProperties: [...existingProps, ...props],
140
+ },
141
+ });
142
+ }
143
+ /**
144
+ * Extract subgraph starting from these root IDs
145
+ */
146
+ subgraph(rootIds) {
147
+ const existingRoots = this.config.filters?.subgraphRoots || [];
148
+ return this.createInstance({
149
+ ...this.config,
150
+ filters: {
151
+ ...this.config.filters,
152
+ subgraphRoots: [...existingRoots, ...rootIds],
153
+ },
154
+ });
155
+ }
156
+ /**
157
+ * Filter properties for specific entity IDs
158
+ */
159
+ filterPropertiesByIds(entityIds, rule) {
160
+ const existingRules = this.config.filters?.propertyFiltersByIds || [];
161
+ const newRule = {
162
+ entityIds,
163
+ ...rule,
164
+ };
165
+ return this.createInstance({
166
+ ...this.config,
167
+ filters: {
168
+ ...this.config.filters,
169
+ propertyFiltersByIds: [...existingRules, newRule],
170
+ },
171
+ });
172
+ }
173
+ /**
174
+ * Filter properties for specific entity types
175
+ */
176
+ filterPropertiesByTypes(entityTypes, rule) {
177
+ const existingRules = this.config.filters?.propertyFiltersByTypes || [];
178
+ const newRule = {
179
+ entityTypes,
180
+ ...rule,
181
+ };
182
+ return this.createInstance({
183
+ ...this.config,
184
+ filters: {
185
+ ...this.config.filters,
186
+ propertyFiltersByTypes: [...existingRules, newRule],
187
+ },
188
+ });
189
+ }
190
+ /**
191
+ * Add additional entities
192
+ */
193
+ addEntities(entities) {
194
+ const existingEntities = this.config.additionalEntities || [];
195
+ return this.createInstance({
196
+ ...this.config,
197
+ additionalEntities: [...existingEntities, ...entities],
198
+ });
199
+ }
200
+ /**
201
+ * Add custom transformation pipe
202
+ */
203
+ pipe(fn) {
204
+ const existingPipes = this.config.pipes || [];
205
+ return this.createInstance({
206
+ ...this.config,
207
+ pipes: [...existingPipes, fn],
208
+ });
209
+ }
210
+ /**
211
+ * Configure entity population
212
+ */
213
+ populateEntities(entityIds, populateConfig) {
214
+ // Merge with existing populate config
215
+ const existingPopulateConfig = this.config.populateConfig || {};
216
+ const mergedPopulateConfig = { ...existingPopulateConfig };
217
+ // Add the new populate config for the specified entity IDs
218
+ for (const entityId of entityIds) {
219
+ if (populateConfig[entityId]) {
220
+ mergedPopulateConfig[entityId] = populateConfig[entityId];
221
+ }
222
+ }
223
+ return this.createInstance({
224
+ ...this.config,
225
+ populateConfig: mergedPopulateConfig,
226
+ });
227
+ }
228
+ /**
229
+ * Clear both includeIds and excludeIds
230
+ * @example
231
+ * ```typescript
232
+ * config.includeIds(['a']).excludeIds(['b']).clearIds().includeIds(['c'])
233
+ * // Result: only includes 'c', previous IDs are cleared
234
+ * ```
235
+ */
236
+ clearIds() {
237
+ return this.createInstance({
238
+ ...this.config,
239
+ filters: {
240
+ ...this.config.filters,
241
+ includeIds: undefined,
242
+ excludeIds: undefined,
243
+ },
244
+ });
245
+ }
246
+ /**
247
+ * Clear both includeTypes and excludeTypes
248
+ */
249
+ clearTypes() {
250
+ return this.createInstance({
251
+ ...this.config,
252
+ filters: {
253
+ ...this.config.filters,
254
+ includeTypes: undefined,
255
+ excludeTypes: undefined,
256
+ },
257
+ });
258
+ }
259
+ /**
260
+ * Clear both requiredProperties and excludeEntitiesWithProperties
261
+ */
262
+ clearPropertyRequirements() {
263
+ return this.createInstance({
264
+ ...this.config,
265
+ filters: {
266
+ ...this.config.filters,
267
+ requiredProperties: undefined,
268
+ excludeEntitiesWithProperties: undefined,
269
+ },
270
+ });
271
+ }
272
+ /**
273
+ * Clear both propertyFiltersByIds and propertyFiltersByTypes
274
+ */
275
+ clearPropertyFilters() {
276
+ return this.createInstance({
277
+ ...this.config,
278
+ filters: {
279
+ ...this.config.filters,
280
+ propertyFiltersByIds: undefined,
281
+ propertyFiltersByTypes: undefined,
282
+ },
283
+ });
284
+ }
285
+ /**
286
+ * Clear subgraphRoots
287
+ */
288
+ clearSubgraph() {
289
+ return this.createInstance({
290
+ ...this.config,
291
+ filters: {
292
+ ...this.config.filters,
293
+ subgraphRoots: undefined,
294
+ },
295
+ });
296
+ }
297
+ /**
298
+ * Clear entire configuration except baseGraph
299
+ * @example
300
+ * ```typescript
301
+ * config.baseGraph(graph).includeIds(['a']).clearAll().includeTypes(['Person'])
302
+ * // Result: only baseGraph and includeTypes remain
303
+ * ```
304
+ */
305
+ clearAll() {
306
+ return this.createInstance({
307
+ baseGraph: this.config.baseGraph,
308
+ });
309
+ }
310
+ /**
311
+ * Merge with another configuration
312
+ * @param config - Configuration to merge with current configuration
313
+ */
314
+ mergeConfig(config) {
315
+ const currentConfig = this.getConfig();
316
+ const mergedConfig = (0, builder_utils_1.mergeConfigs)(currentConfig, config);
317
+ return this.createInstance(mergedConfig);
318
+ }
319
+ /**
320
+ * Merge only the filters part of another configuration
321
+ * @param filters - Filter options to merge with current filters
322
+ */
323
+ mergeFilters(filters) {
324
+ const currentFilters = this.config.filters;
325
+ const mergedFilters = (0, builder_utils_1.mergeFilterOptions)(currentFilters, filters);
326
+ return this.createInstance({
327
+ ...this.config,
328
+ filters: mergedFilters,
329
+ });
330
+ }
331
+ /**
332
+ * Get the current configuration
333
+ */
334
+ getConfig() {
335
+ return { ...this.config };
336
+ }
337
+ }
338
+ exports.JsonLdConfigBuilder = JsonLdConfigBuilder;
339
+ /**
340
+ * Factory function to create a new configuration builder
341
+ */
342
+ function createJsonLdConfig() {
343
+ return new JsonLdConfigBuilder();
344
+ }
@@ -0,0 +1,255 @@
1
+ /**
2
+ * Utility functions for JSON-LD builder
3
+ *
4
+ * Provides configuration merging, validation, and transformation utilities
5
+ * for the JSON-LD builder system.
6
+ */
7
+ /**
8
+ * Merge two configurations, with the second taking precedence
9
+ */
10
+ export function mergeConfigs(base, override) {
11
+ return {
12
+ // Base graph: override takes precedence
13
+ baseGraph: override.baseGraph ?? base.baseGraph,
14
+ // Filters: merge filter options
15
+ filters: mergeFilterOptions(base.filters, override.filters),
16
+ // Additional entities: combine arrays
17
+ additionalEntities: combineArrays(base.additionalEntities, override.additionalEntities),
18
+ // Pipes: combine arrays
19
+ pipes: combineArrays(base.pipes, override.pipes),
20
+ // Populate config: override takes precedence
21
+ populateConfig: override.populateConfig ?? base.populateConfig,
22
+ };
23
+ }
24
+ /**
25
+ * Merge filter options, merging arrays and using override for single values
26
+ */
27
+ export function mergeFilterOptions(base, override) {
28
+ if (!base && !override)
29
+ return undefined;
30
+ if (!base)
31
+ return override;
32
+ if (!override)
33
+ return base;
34
+ return {
35
+ // Merge arrays instead of replacing
36
+ includeTypes: combineArrays(base.includeTypes, override.includeTypes),
37
+ excludeTypes: combineArrays(base.excludeTypes, override.excludeTypes),
38
+ includeIds: combineArrays(base.includeIds, override.includeIds),
39
+ excludeIds: combineArrays(base.excludeIds, override.excludeIds),
40
+ requiredProperties: combineArrays(base.requiredProperties, override.requiredProperties),
41
+ excludeEntitiesWithProperties: combineArrays(base.excludeEntitiesWithProperties, override.excludeEntitiesWithProperties),
42
+ subgraphRoots: combineArrays(base.subgraphRoots, override.subgraphRoots),
43
+ propertyFilters: combinePropertyFilters(base.propertyFilters, override.propertyFilters),
44
+ propertyFiltersByIds: combineArrays(base.propertyFiltersByIds, override.propertyFiltersByIds),
45
+ propertyFiltersByTypes: combineArrays(base.propertyFiltersByTypes, override.propertyFiltersByTypes),
46
+ // Single values - override takes precedence
47
+ customFilter: override.customFilter ?? base.customFilter,
48
+ maxEntities: override.maxEntities ?? base.maxEntities,
49
+ };
50
+ }
51
+ /**
52
+ * Combine property filter configurations
53
+ */
54
+ function combinePropertyFilters(base, override) {
55
+ if (!base && !override)
56
+ return undefined;
57
+ if (!base)
58
+ return override;
59
+ if (!override)
60
+ return base;
61
+ return [...base, ...override];
62
+ }
63
+ /**
64
+ * Combine arrays, handling undefined values
65
+ */
66
+ function combineArrays(base, override) {
67
+ if (!base && !override)
68
+ return undefined;
69
+ if (!base)
70
+ return override;
71
+ if (!override)
72
+ return base;
73
+ return [...base, ...override];
74
+ }
75
+ /**
76
+ * Convert property filter by ID rules to PropertyFilterConfig
77
+ */
78
+ export function convertPropertyFiltersByIds(rules) {
79
+ return rules.flatMap((rule) => rule.entityIds.map((entityId) => ({
80
+ selector: { '@id': entityId },
81
+ include: rule.include,
82
+ exclude: rule.exclude,
83
+ })));
84
+ }
85
+ /**
86
+ * Convert property filter by type rules to PropertyFilterConfig
87
+ */
88
+ export function convertPropertyFiltersByTypes(rules) {
89
+ return rules.flatMap((rule) => rule.entityTypes.map((entityType) => ({
90
+ selector: { '@type': entityType },
91
+ include: rule.include,
92
+ exclude: rule.exclude,
93
+ })));
94
+ }
95
+ /**
96
+ * Build complete property filter configuration from all sources
97
+ */
98
+ export function buildPropertyFilterConfig(config) {
99
+ const filters = [];
100
+ // Add base property filters
101
+ if (config.filters?.propertyFilters) {
102
+ filters.push(...config.filters.propertyFilters);
103
+ }
104
+ // Add property filters by IDs
105
+ if (config.filters?.propertyFiltersByIds) {
106
+ filters.push(...convertPropertyFiltersByIds(config.filters.propertyFiltersByIds));
107
+ }
108
+ // Add property filters by types
109
+ if (config.filters?.propertyFiltersByTypes) {
110
+ filters.push(...convertPropertyFiltersByTypes(config.filters.propertyFiltersByTypes));
111
+ }
112
+ return filters.length > 0 ? filters : undefined;
113
+ }
114
+ /**
115
+ * Validate configuration for common issues
116
+ */
117
+ export function validateConfig(config) {
118
+ const errors = [];
119
+ // Check for conflicting include/exclude types
120
+ if (config.filters?.includeTypes && config.filters?.excludeTypes) {
121
+ const overlap = config.filters.includeTypes.filter((type) => config.filters.excludeTypes.includes(type));
122
+ if (overlap.length > 0) {
123
+ errors.push(`Conflicting include/exclude types: ${overlap.join(', ')}`);
124
+ }
125
+ }
126
+ // Check for conflicting include/exclude IDs
127
+ if (config.filters?.includeIds && config.filters?.excludeIds) {
128
+ const overlap = config.filters.includeIds.filter((id) => config.filters.excludeIds.includes(id));
129
+ if (overlap.length > 0) {
130
+ errors.push(`Conflicting include/exclude IDs: ${overlap.join(', ')}`);
131
+ }
132
+ }
133
+ // Check for invalid maxEntities
134
+ if (config.filters?.maxEntities !== undefined && config.filters.maxEntities < 1) {
135
+ errors.push('maxEntities must be greater than 0');
136
+ }
137
+ return errors;
138
+ }
139
+ /**
140
+ * Apply populate configuration to entities in the graph
141
+ */
142
+ export function applyPopulateConfig(graph, populateConfig) {
143
+ return graph.map((entity) => {
144
+ const entityId = entity['@id'];
145
+ const populateRules = populateConfig[entityId];
146
+ if (!populateRules || populateRules.length === 0) {
147
+ return entity;
148
+ }
149
+ // Create a copy of the entity to avoid mutation
150
+ const populatedEntity = { ...entity };
151
+ // Apply each populate rule
152
+ for (const rule of populateRules) {
153
+ populatedEntity[rule.property] = rule.entities;
154
+ }
155
+ return populatedEntity;
156
+ });
157
+ }
158
+ /**
159
+ * Validate runtime configuration for critical errors only
160
+ * This is more lenient than the general validateConfig to handle runtime overrides
161
+ */
162
+ export function validateRuntimeConfig(config) {
163
+ const errors = [];
164
+ // Check for baseGraph requirement
165
+ if (!config.baseGraph) {
166
+ errors.push('baseGraph is required');
167
+ }
168
+ else if (!Array.isArray(config.baseGraph)) {
169
+ errors.push('baseGraph must be an array');
170
+ }
171
+ // Only check for critical errors that would break processing
172
+ if (config.filters?.maxEntities !== undefined && config.filters.maxEntities < 1) {
173
+ errors.push('maxEntities must be greater than 0');
174
+ }
175
+ return errors;
176
+ }
177
+ /**
178
+ * Type guard to check if an entity matches a type
179
+ */
180
+ export function entityHasType(entity, type) {
181
+ const entityType = entity['@type'];
182
+ if (!entityType)
183
+ return false;
184
+ if (Array.isArray(entityType)) {
185
+ return entityType.includes(type);
186
+ }
187
+ return entityType === type;
188
+ }
189
+ /**
190
+ * Type guard to check if an entity has any of the specified types
191
+ */
192
+ export function entityHasAnyType(entity, types) {
193
+ return types.some((type) => entityHasType(entity, type));
194
+ }
195
+ /**
196
+ * Get all types from an entity as an array
197
+ */
198
+ export function getEntityTypes(entity) {
199
+ const entityType = entity['@type'];
200
+ if (!entityType)
201
+ return [];
202
+ return Array.isArray(entityType) ? entityType : [entityType];
203
+ }
204
+ /**
205
+ * Apply filters to a JSON-LD graph (copied from head-manager/filters.ts for self-containment)
206
+ */
207
+ export function filterJsonLdGraph(graph, options) {
208
+ let filtered = [...graph];
209
+ // Apply type inclusion filter
210
+ if (options.includeTypes && options.includeTypes.length > 0) {
211
+ filtered = filtered.filter((entity) => {
212
+ const type = entity['@type'];
213
+ if (!type)
214
+ return false;
215
+ const types = Array.isArray(type) ? type : [type];
216
+ return types.some((t) => options.includeTypes.includes(t));
217
+ });
218
+ }
219
+ // Apply type exclusion filter
220
+ if (options.excludeTypes && options.excludeTypes.length > 0) {
221
+ filtered = filtered.filter((entity) => {
222
+ const type = entity['@type'];
223
+ if (!type)
224
+ return true;
225
+ const types = Array.isArray(type) ? type : [type];
226
+ return !types.some((t) => options.excludeTypes.includes(t));
227
+ });
228
+ }
229
+ // Apply ID inclusion filter
230
+ if (options.includeIds && options.includeIds.length > 0) {
231
+ filtered = filtered.filter((entity) => entity['@id'] && options.includeIds.includes(entity['@id']));
232
+ }
233
+ // Apply ID exclusion filter
234
+ if (options.excludeIds && options.excludeIds.length > 0) {
235
+ filtered = filtered.filter((entity) => !entity['@id'] || !options.excludeIds.includes(entity['@id']));
236
+ }
237
+ // Apply required properties filter
238
+ if (options.requiredProperties && options.requiredProperties.length > 0) {
239
+ filtered = filtered.filter((entity) => options.requiredProperties.every((prop) => prop in entity));
240
+ }
241
+ // Apply excluded properties filter (handle both old and new property names)
242
+ const excludeProps = options.excludeEntitiesWithProperties || options.excludeProperties;
243
+ if (excludeProps && excludeProps.length > 0) {
244
+ filtered = filtered.filter((entity) => !excludeProps.some((prop) => prop in entity));
245
+ }
246
+ // Apply custom filter
247
+ if (options.customFilter) {
248
+ filtered = filtered.filter(options.customFilter);
249
+ }
250
+ // Apply max entities limit
251
+ if (options.maxEntities && options.maxEntities > 0) {
252
+ filtered = filtered.slice(0, options.maxEntities);
253
+ }
254
+ return filtered;
255
+ }