@contentrain/query 3.2.0 → 5.0.0
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/LICENSE +21 -21
- package/README.md +246 -268
- package/dist/cli.cjs +78 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +81 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/generate-C5Qz8qKt.mjs +855 -0
- package/dist/generate-C5Qz8qKt.mjs.map +1 -0
- package/dist/generate-CPKYh6ZU.cjs +858 -0
- package/dist/generator/generate.cjs +3 -0
- package/dist/generator/generate.d.cts +14 -0
- package/dist/generator/generate.d.cts.map +1 -0
- package/dist/generator/generate.d.mts +14 -0
- package/dist/generator/generate.d.mts.map +1 -0
- package/dist/generator/generate.mjs +2 -0
- package/dist/index.cjs +356 -0
- package/dist/index.d.cts +108 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +107 -290
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +343 -859
- package/dist/index.mjs.map +1 -1
- package/package.json +46 -29
- package/dist/index.d.ts +0 -291
- package/dist/index.js +0 -872
- package/dist/index.js.map +0 -1
package/dist/index.js
DELETED
|
@@ -1,872 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
var promises = require('fs/promises');
|
|
4
|
-
var path = require('path');
|
|
5
|
-
var tinyLru = require('tiny-lru');
|
|
6
|
-
var process = require('process');
|
|
7
|
-
|
|
8
|
-
var __defProp = Object.defineProperty;
|
|
9
|
-
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
10
|
-
var isDevelopment = process.env.NODE_ENV === "development";
|
|
11
|
-
var logger = {
|
|
12
|
-
debug: /* @__PURE__ */ __name((...args) => {
|
|
13
|
-
if (isDevelopment) {
|
|
14
|
-
console.log(...args);
|
|
15
|
-
}
|
|
16
|
-
}, "debug"),
|
|
17
|
-
error: /* @__PURE__ */ __name((...args) => {
|
|
18
|
-
if (isDevelopment) {
|
|
19
|
-
console.error(...args);
|
|
20
|
-
}
|
|
21
|
-
}, "error")
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
// src/cache/memory.ts
|
|
25
|
-
var _MemoryCache = class _MemoryCache {
|
|
26
|
-
constructor(options = {}) {
|
|
27
|
-
this.stats = {
|
|
28
|
-
hits: 0,
|
|
29
|
-
misses: 0,
|
|
30
|
-
size: 0,
|
|
31
|
-
lastCleanup: Date.now()
|
|
32
|
-
};
|
|
33
|
-
this.options = {
|
|
34
|
-
maxSize: 100,
|
|
35
|
-
// 100 MB
|
|
36
|
-
defaultTTL: 60 * 1e3,
|
|
37
|
-
// 1 dakika
|
|
38
|
-
...options
|
|
39
|
-
};
|
|
40
|
-
const maxItems = Math.floor(this.options.maxSize * 1024 * 1024 / 1e3);
|
|
41
|
-
this.cache = tinyLru.lru(maxItems);
|
|
42
|
-
}
|
|
43
|
-
calculateSize(data) {
|
|
44
|
-
const str = JSON.stringify(data);
|
|
45
|
-
return new TextEncoder().encode(str).length;
|
|
46
|
-
}
|
|
47
|
-
async set(key, data, ttl) {
|
|
48
|
-
logger.debug("Saving data to cache:", {
|
|
49
|
-
key,
|
|
50
|
-
ttl
|
|
51
|
-
});
|
|
52
|
-
await this.cleanupCache();
|
|
53
|
-
const size = this.calculateSize(data);
|
|
54
|
-
const now = Date.now();
|
|
55
|
-
const expireAt = now + (ttl || this.options.defaultTTL);
|
|
56
|
-
while (size + this.stats.size > this.options.maxSize * 1024 * 1024) {
|
|
57
|
-
const oldestKey = this.findOldestKey();
|
|
58
|
-
if (!oldestKey)
|
|
59
|
-
break;
|
|
60
|
-
await this.delete(oldestKey);
|
|
61
|
-
}
|
|
62
|
-
const entry = {
|
|
63
|
-
data,
|
|
64
|
-
expireAt,
|
|
65
|
-
size,
|
|
66
|
-
createdAt: now
|
|
67
|
-
};
|
|
68
|
-
const oldEntry = this.cache.get(key);
|
|
69
|
-
if (oldEntry) {
|
|
70
|
-
this.stats.size -= oldEntry.size;
|
|
71
|
-
}
|
|
72
|
-
this.cache.set(key, entry);
|
|
73
|
-
this.stats.size += size;
|
|
74
|
-
logger.debug("Data saved to cache:", {
|
|
75
|
-
key,
|
|
76
|
-
expiry: expireAt ? new Date(expireAt).toISOString() : "no expiry"
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
|
-
findOldestKey() {
|
|
80
|
-
let oldestKey = null;
|
|
81
|
-
let oldestTime = Infinity;
|
|
82
|
-
for (const key of this.cache.keys()) {
|
|
83
|
-
const entry = this.cache.get(key);
|
|
84
|
-
if (entry.createdAt < oldestTime) {
|
|
85
|
-
oldestTime = entry.createdAt;
|
|
86
|
-
oldestKey = key;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
return oldestKey;
|
|
90
|
-
}
|
|
91
|
-
async get(key) {
|
|
92
|
-
logger.debug("Getting data from cache:", { key });
|
|
93
|
-
const entry = this.cache.get(key);
|
|
94
|
-
if (!entry) {
|
|
95
|
-
logger.debug("Data not found in cache:", { key });
|
|
96
|
-
this.stats.misses++;
|
|
97
|
-
return null;
|
|
98
|
-
}
|
|
99
|
-
if (Date.now() >= entry.expireAt) {
|
|
100
|
-
await this.delete(key);
|
|
101
|
-
this.stats.misses++;
|
|
102
|
-
return null;
|
|
103
|
-
}
|
|
104
|
-
logger.debug("Data retrieved from cache:", {
|
|
105
|
-
key,
|
|
106
|
-
expiry: entry.expireAt ? new Date(entry.expireAt).toISOString() : "no expiry"
|
|
107
|
-
});
|
|
108
|
-
this.stats.hits++;
|
|
109
|
-
return entry.data;
|
|
110
|
-
}
|
|
111
|
-
async delete(key) {
|
|
112
|
-
logger.debug("Deleting data from cache:", { key });
|
|
113
|
-
const entry = this.cache.get(key);
|
|
114
|
-
if (entry) {
|
|
115
|
-
this.stats.size -= entry.size;
|
|
116
|
-
this.cache.delete(key);
|
|
117
|
-
}
|
|
118
|
-
logger.debug("Data deleted from cache:", { key });
|
|
119
|
-
}
|
|
120
|
-
async clear() {
|
|
121
|
-
logger.debug("Clearing cache");
|
|
122
|
-
this.cache.clear();
|
|
123
|
-
this.stats = {
|
|
124
|
-
hits: 0,
|
|
125
|
-
misses: 0,
|
|
126
|
-
size: 0,
|
|
127
|
-
lastCleanup: Date.now()
|
|
128
|
-
};
|
|
129
|
-
logger.debug("Cache cleared");
|
|
130
|
-
}
|
|
131
|
-
async cleanupCache() {
|
|
132
|
-
const now = Date.now();
|
|
133
|
-
const expiredKeys = [];
|
|
134
|
-
let totalSize = 0;
|
|
135
|
-
for (const key of this.cache.keys()) {
|
|
136
|
-
const entry = this.cache.get(key);
|
|
137
|
-
if (entry.expireAt <= now) {
|
|
138
|
-
expiredKeys.push(key);
|
|
139
|
-
} else {
|
|
140
|
-
totalSize += entry.size;
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
for (const key of expiredKeys) {
|
|
144
|
-
await this.delete(key);
|
|
145
|
-
}
|
|
146
|
-
while (totalSize > this.options.maxSize * 1024 * 1024) {
|
|
147
|
-
const oldestKey = this.findOldestKey();
|
|
148
|
-
if (!oldestKey)
|
|
149
|
-
break;
|
|
150
|
-
const entry = this.cache.get(oldestKey);
|
|
151
|
-
await this.delete(oldestKey);
|
|
152
|
-
totalSize -= entry.size;
|
|
153
|
-
}
|
|
154
|
-
this.stats.lastCleanup = now;
|
|
155
|
-
}
|
|
156
|
-
getStats() {
|
|
157
|
-
return { ...this.stats };
|
|
158
|
-
}
|
|
159
|
-
};
|
|
160
|
-
__name(_MemoryCache, "MemoryCache");
|
|
161
|
-
var MemoryCache = _MemoryCache;
|
|
162
|
-
|
|
163
|
-
// src/loader/content.ts
|
|
164
|
-
var _ContentLoader = class _ContentLoader {
|
|
165
|
-
constructor(options) {
|
|
166
|
-
this.modelConfigs = /* @__PURE__ */ new Map();
|
|
167
|
-
this.relations = /* @__PURE__ */ new Map();
|
|
168
|
-
this.options = {
|
|
169
|
-
defaultLocale: "en",
|
|
170
|
-
cache: true,
|
|
171
|
-
ttl: 60 * 1e3,
|
|
172
|
-
// 1 minute
|
|
173
|
-
maxCacheSize: 100,
|
|
174
|
-
// 100 MB
|
|
175
|
-
...options
|
|
176
|
-
};
|
|
177
|
-
this.cache = new MemoryCache({
|
|
178
|
-
maxSize: this.options.maxCacheSize,
|
|
179
|
-
defaultTTL: this.options.ttl
|
|
180
|
-
});
|
|
181
|
-
}
|
|
182
|
-
getCacheKey(model) {
|
|
183
|
-
return `${model}`;
|
|
184
|
-
}
|
|
185
|
-
getModelTTL(model) {
|
|
186
|
-
return this.options.modelTTL?.[model] || this.options.ttl || 0;
|
|
187
|
-
}
|
|
188
|
-
async clearCache() {
|
|
189
|
-
await this.cache.clear();
|
|
190
|
-
}
|
|
191
|
-
async refreshCache(model) {
|
|
192
|
-
const cacheKey = this.getCacheKey(model);
|
|
193
|
-
await this.cache.delete(cacheKey);
|
|
194
|
-
await this.load(model);
|
|
195
|
-
}
|
|
196
|
-
getCacheStats() {
|
|
197
|
-
return this.cache.getStats();
|
|
198
|
-
}
|
|
199
|
-
async loadModelConfig(model) {
|
|
200
|
-
try {
|
|
201
|
-
const metadataPath = path.join(this.options.contentDir, "models", "metadata.json");
|
|
202
|
-
const metadataContent = await promises.readFile(metadataPath, "utf-8");
|
|
203
|
-
const allMetadata = JSON.parse(metadataContent);
|
|
204
|
-
const modelMetadata = allMetadata.find((m) => m.modelId === model);
|
|
205
|
-
if (!modelMetadata) {
|
|
206
|
-
logger.error("Model metadata not found:", {
|
|
207
|
-
model,
|
|
208
|
-
metadataPath
|
|
209
|
-
});
|
|
210
|
-
throw new Error(`Model metadata not found for ${model}`);
|
|
211
|
-
}
|
|
212
|
-
const modelPath = path.join(this.options.contentDir, "models", `${model}.json`);
|
|
213
|
-
const modelContent = await promises.readFile(modelPath, "utf-8");
|
|
214
|
-
const modelFields = JSON.parse(modelContent);
|
|
215
|
-
return {
|
|
216
|
-
metadata: modelMetadata,
|
|
217
|
-
fields: modelFields
|
|
218
|
-
};
|
|
219
|
-
} catch (error) {
|
|
220
|
-
logger.error("Failed to load model config:", {
|
|
221
|
-
model,
|
|
222
|
-
error: error?.message || "Unknown error"
|
|
223
|
-
});
|
|
224
|
-
throw new Error(`Failed to load model config for ${model}: ${error?.message || "Unknown error"}`);
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
async loadContentFile(model, locale = "default") {
|
|
228
|
-
try {
|
|
229
|
-
const modelConfig = await this.loadModelConfig(model);
|
|
230
|
-
let contentPath;
|
|
231
|
-
if (modelConfig.metadata.localization) {
|
|
232
|
-
if (!locale || locale === "default") {
|
|
233
|
-
if (!this.options.defaultLocale) {
|
|
234
|
-
logger.error("Default locale is required for localized model:", {
|
|
235
|
-
model
|
|
236
|
-
});
|
|
237
|
-
throw new Error(`Default locale is required for localized model "${model}"`);
|
|
238
|
-
}
|
|
239
|
-
locale = this.options.defaultLocale;
|
|
240
|
-
}
|
|
241
|
-
contentPath = path.join(this.options.contentDir, model, `${locale}.json`);
|
|
242
|
-
} else {
|
|
243
|
-
if (locale !== "default") {
|
|
244
|
-
console.warn(`Locale "${locale}" specified for non-localized model "${model}". This parameter will be ignored.`);
|
|
245
|
-
}
|
|
246
|
-
contentPath = path.join(this.options.contentDir, model, `${model}.json`);
|
|
247
|
-
}
|
|
248
|
-
const content = await promises.readFile(contentPath, "utf-8");
|
|
249
|
-
try {
|
|
250
|
-
const data = JSON.parse(content);
|
|
251
|
-
return {
|
|
252
|
-
model,
|
|
253
|
-
locale: modelConfig.metadata.localization ? locale : void 0,
|
|
254
|
-
data
|
|
255
|
-
};
|
|
256
|
-
} catch {
|
|
257
|
-
logger.error("Failed to load content:", {
|
|
258
|
-
model,
|
|
259
|
-
locale,
|
|
260
|
-
contentPath
|
|
261
|
-
});
|
|
262
|
-
throw new Error(`Failed to load content: Invalid JSON format in ${contentPath}`);
|
|
263
|
-
}
|
|
264
|
-
} catch (error) {
|
|
265
|
-
if (error.message.includes("Invalid JSON format")) {
|
|
266
|
-
logger.error("Failed to load content:", {
|
|
267
|
-
model,
|
|
268
|
-
locale
|
|
269
|
-
});
|
|
270
|
-
throw error;
|
|
271
|
-
}
|
|
272
|
-
throw new Error(
|
|
273
|
-
`Failed to load content file for ${model}${locale ? ` (${locale})` : ""}: ${error?.message || "Unknown error"}`
|
|
274
|
-
);
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
async loadRelations(model) {
|
|
278
|
-
try {
|
|
279
|
-
const modelConfig = this.modelConfigs.get(model);
|
|
280
|
-
if (!modelConfig) {
|
|
281
|
-
throw new Error(`Model config not found for ${model}`);
|
|
282
|
-
}
|
|
283
|
-
const relationFields = modelConfig.fields.filter((field) => {
|
|
284
|
-
return field.fieldType === "relation";
|
|
285
|
-
});
|
|
286
|
-
return relationFields.map((field) => {
|
|
287
|
-
const options = field.options;
|
|
288
|
-
const reference = options?.reference?.form?.reference?.value;
|
|
289
|
-
if (!reference) {
|
|
290
|
-
throw new Error(`Reference not found for relation field: ${field.name}`);
|
|
291
|
-
}
|
|
292
|
-
return {
|
|
293
|
-
model: reference,
|
|
294
|
-
type: field.componentId === "one-to-one" ? "one-to-one" : "one-to-many",
|
|
295
|
-
foreignKey: field.fieldId
|
|
296
|
-
};
|
|
297
|
-
});
|
|
298
|
-
} catch (error) {
|
|
299
|
-
throw new Error(`Failed to load relations for ${model}: ${error?.message || "Unknown error"}`);
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
async getModelLocales(model, modelConfig) {
|
|
303
|
-
try {
|
|
304
|
-
if (!modelConfig.metadata.localization) {
|
|
305
|
-
return ["default"];
|
|
306
|
-
}
|
|
307
|
-
const modelDir = path.join(this.options.contentDir, model);
|
|
308
|
-
const files = await promises.readdir(modelDir);
|
|
309
|
-
const locales = files.filter((file) => file.endsWith(".json")).map((file) => file.replace(".json", "")).filter((locale) => locale !== model);
|
|
310
|
-
if (locales.length === 0) {
|
|
311
|
-
if (!this.options.defaultLocale) {
|
|
312
|
-
throw new Error(`No locale files found for localized model "${model}" and no default locale specified`);
|
|
313
|
-
}
|
|
314
|
-
return [this.options.defaultLocale];
|
|
315
|
-
}
|
|
316
|
-
return locales;
|
|
317
|
-
} catch (error) {
|
|
318
|
-
if (!this.options.defaultLocale) {
|
|
319
|
-
throw new Error(`Failed to read locales for model ${model} and no default locale specified: ${error?.message}`);
|
|
320
|
-
}
|
|
321
|
-
console.warn(`Failed to read locales for model ${model}: ${error?.message}`);
|
|
322
|
-
return [this.options.defaultLocale];
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
async load(model) {
|
|
326
|
-
const cacheKey = `${model}`;
|
|
327
|
-
if (this.options.cache) {
|
|
328
|
-
const cached = await this.cache.get(cacheKey);
|
|
329
|
-
if (cached)
|
|
330
|
-
return cached;
|
|
331
|
-
}
|
|
332
|
-
const modelConfig = await this.loadModelConfig(model);
|
|
333
|
-
this.modelConfigs.set(model, modelConfig);
|
|
334
|
-
const relations = await this.loadRelations(model);
|
|
335
|
-
this.relations.set(model, relations);
|
|
336
|
-
const content = {};
|
|
337
|
-
if (modelConfig.metadata.localization) {
|
|
338
|
-
const locales = await this.getModelLocales(model, modelConfig);
|
|
339
|
-
for (const locale of locales) {
|
|
340
|
-
try {
|
|
341
|
-
const file = await this.loadContentFile(model, locale);
|
|
342
|
-
content[locale] = file.data;
|
|
343
|
-
} catch (error) {
|
|
344
|
-
console.warn(`Failed to load content for locale ${locale}: ${error?.message}`);
|
|
345
|
-
if (locale === this.options.defaultLocale) {
|
|
346
|
-
throw error;
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
} else {
|
|
351
|
-
const file = await this.loadContentFile(model);
|
|
352
|
-
content.default = file.data;
|
|
353
|
-
}
|
|
354
|
-
let assets = [];
|
|
355
|
-
try {
|
|
356
|
-
const assetsPath = path.join(this.options.contentDir, "assets.json");
|
|
357
|
-
const assetsContent = await promises.readFile(assetsPath, "utf-8");
|
|
358
|
-
assets = JSON.parse(assetsContent);
|
|
359
|
-
} catch (error) {
|
|
360
|
-
console.warn("Assets file not found or cannot be read:", error);
|
|
361
|
-
}
|
|
362
|
-
const result = {
|
|
363
|
-
model: modelConfig,
|
|
364
|
-
content,
|
|
365
|
-
assets
|
|
366
|
-
};
|
|
367
|
-
if (this.options.cache) {
|
|
368
|
-
const ttl = this.getModelTTL(model);
|
|
369
|
-
await this.cache.set(cacheKey, result, ttl);
|
|
370
|
-
}
|
|
371
|
-
return result;
|
|
372
|
-
}
|
|
373
|
-
async resolveRelation(model, relationField, data, locale) {
|
|
374
|
-
try {
|
|
375
|
-
logger.debug("Debug - Starting relation resolution:", {
|
|
376
|
-
model,
|
|
377
|
-
relationField,
|
|
378
|
-
dataLength: data.length,
|
|
379
|
-
locale
|
|
380
|
-
});
|
|
381
|
-
const relations = this.relations.get(model);
|
|
382
|
-
logger.debug("Debug - Relations:", relations);
|
|
383
|
-
if (!relations)
|
|
384
|
-
throw new Error(`No relations found for model: ${model}`);
|
|
385
|
-
const relation = relations.find((r) => r.foreignKey === relationField);
|
|
386
|
-
logger.debug("Debug - Found relation:", relation);
|
|
387
|
-
if (!relation)
|
|
388
|
-
throw new Error(`No relation found for field: ${String(relationField)}`);
|
|
389
|
-
logger.debug("Debug - Related model loading:", relation.model);
|
|
390
|
-
const relatedContent = await this.load(relation.model);
|
|
391
|
-
logger.debug("Debug - \u0130li\u015Fkili model y\xFCklendi:", {
|
|
392
|
-
model: relation.model,
|
|
393
|
-
metadata: relatedContent.model.metadata,
|
|
394
|
-
contentKeys: Object.keys(relatedContent.content)
|
|
395
|
-
});
|
|
396
|
-
let relatedData;
|
|
397
|
-
if (relatedContent.model.metadata.localization) {
|
|
398
|
-
logger.debug("Debug - Processing localized model");
|
|
399
|
-
const localizedContent = locale ? relatedContent.content[locale] : relatedContent.content.en;
|
|
400
|
-
logger.debug("Debug - Localized content:", {
|
|
401
|
-
locale: locale || "en",
|
|
402
|
-
contentType: typeof localizedContent,
|
|
403
|
-
isArray: Array.isArray(localizedContent)
|
|
404
|
-
});
|
|
405
|
-
if (!Array.isArray(localizedContent)) {
|
|
406
|
-
throw new TypeError(`Invalid content format for localized model ${relation.model}`);
|
|
407
|
-
}
|
|
408
|
-
relatedData = localizedContent;
|
|
409
|
-
} else {
|
|
410
|
-
logger.debug("Debug - Processing non-localized model");
|
|
411
|
-
const nonLocalizedContent = relatedContent.content.default;
|
|
412
|
-
logger.debug("Debug - Raw content:", {
|
|
413
|
-
contentType: typeof nonLocalizedContent,
|
|
414
|
-
isArray: Array.isArray(nonLocalizedContent),
|
|
415
|
-
content: nonLocalizedContent
|
|
416
|
-
});
|
|
417
|
-
if (!Array.isArray(nonLocalizedContent)) {
|
|
418
|
-
throw new TypeError(`Invalid content format for non-localized model ${relation.model}`);
|
|
419
|
-
}
|
|
420
|
-
relatedData = nonLocalizedContent;
|
|
421
|
-
}
|
|
422
|
-
logger.debug("Debug - Related data ready:", {
|
|
423
|
-
dataLength: relatedData.length,
|
|
424
|
-
firstItem: relatedData[0]
|
|
425
|
-
});
|
|
426
|
-
if (!relatedData) {
|
|
427
|
-
throw new Error(`Failed to resolve relation: No data found for model ${relation.model}`);
|
|
428
|
-
}
|
|
429
|
-
if (relation.type === "one-to-one") {
|
|
430
|
-
logger.debug("Debug - Processing one-to-one relation");
|
|
431
|
-
const itemsWithRelation = data.filter((item) => item[relationField] !== void 0);
|
|
432
|
-
logger.debug("Debug - Items with relations:", itemsWithRelation.length);
|
|
433
|
-
return itemsWithRelation.map((item) => {
|
|
434
|
-
const relatedItem = relatedData.find((r) => r.ID === item[relationField]);
|
|
435
|
-
if (!relatedItem) {
|
|
436
|
-
throw new Error(`Failed to resolve relation: No matching item found for ID ${String(item[relationField])}`);
|
|
437
|
-
}
|
|
438
|
-
return relatedItem;
|
|
439
|
-
});
|
|
440
|
-
} else {
|
|
441
|
-
logger.debug("Debug - Processing one-to-many relation");
|
|
442
|
-
const uniqueIds = new Set(
|
|
443
|
-
data.flatMap(
|
|
444
|
-
(item) => item[relationField] !== void 0 ? Array.isArray(item[relationField]) ? item[relationField] : [item[relationField]] : []
|
|
445
|
-
)
|
|
446
|
-
);
|
|
447
|
-
logger.debug("Debug - Unique IDs:", Array.from(uniqueIds));
|
|
448
|
-
const items = Array.from(uniqueIds).map((id) => relatedData.find((r) => r.ID === id)).filter(Boolean);
|
|
449
|
-
logger.debug("Debug - Matching items:", items.length);
|
|
450
|
-
if (items.length !== uniqueIds.size) {
|
|
451
|
-
throw new Error("Failed to resolve relation: Some related items not found");
|
|
452
|
-
}
|
|
453
|
-
return items;
|
|
454
|
-
}
|
|
455
|
-
} catch (error) {
|
|
456
|
-
logger.error("Debug - Error occurred:", error);
|
|
457
|
-
throw new Error(`Failed to resolve relation: ${error.message}`);
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
};
|
|
461
|
-
__name(_ContentLoader, "ContentLoader");
|
|
462
|
-
var ContentLoader = _ContentLoader;
|
|
463
|
-
|
|
464
|
-
// src/query/builder.ts
|
|
465
|
-
var _ContentrainQueryBuilder = class _ContentrainQueryBuilder {
|
|
466
|
-
constructor(model, executor, loader) {
|
|
467
|
-
this.filters = [];
|
|
468
|
-
this.includes = {};
|
|
469
|
-
this.sorting = [];
|
|
470
|
-
this.pagination = {};
|
|
471
|
-
this.options = {};
|
|
472
|
-
this.model = model;
|
|
473
|
-
this.executor = executor;
|
|
474
|
-
this.loader = loader;
|
|
475
|
-
}
|
|
476
|
-
where(field, operator, value) {
|
|
477
|
-
logger.debug("Adding filter:", {
|
|
478
|
-
field,
|
|
479
|
-
operator,
|
|
480
|
-
value
|
|
481
|
-
});
|
|
482
|
-
this.filters.push({
|
|
483
|
-
field,
|
|
484
|
-
operator,
|
|
485
|
-
value
|
|
486
|
-
});
|
|
487
|
-
return this;
|
|
488
|
-
}
|
|
489
|
-
include(relation) {
|
|
490
|
-
logger.debug("Adding relation:", relation);
|
|
491
|
-
if (typeof relation === "string") {
|
|
492
|
-
this.includes[relation] = {};
|
|
493
|
-
} else if (Array.isArray(relation)) {
|
|
494
|
-
relation.forEach((r) => {
|
|
495
|
-
this.includes[r] = {};
|
|
496
|
-
});
|
|
497
|
-
}
|
|
498
|
-
return this;
|
|
499
|
-
}
|
|
500
|
-
orderBy(field, direction = "asc") {
|
|
501
|
-
logger.debug("Adding sorting:", {
|
|
502
|
-
field,
|
|
503
|
-
direction
|
|
504
|
-
});
|
|
505
|
-
this.sorting.push({
|
|
506
|
-
field,
|
|
507
|
-
direction
|
|
508
|
-
});
|
|
509
|
-
return this;
|
|
510
|
-
}
|
|
511
|
-
limit(count) {
|
|
512
|
-
logger.debug("Adding limit:", count);
|
|
513
|
-
this.pagination.limit = count;
|
|
514
|
-
return this;
|
|
515
|
-
}
|
|
516
|
-
offset(count) {
|
|
517
|
-
logger.debug("Adding offset:", count);
|
|
518
|
-
this.pagination.offset = count;
|
|
519
|
-
return this;
|
|
520
|
-
}
|
|
521
|
-
locale(code) {
|
|
522
|
-
logger.debug("Setting locale:", code);
|
|
523
|
-
this.options.locale = code;
|
|
524
|
-
return this;
|
|
525
|
-
}
|
|
526
|
-
cache(ttl) {
|
|
527
|
-
logger.debug("Setting cache:", {
|
|
528
|
-
enabled: true,
|
|
529
|
-
ttl
|
|
530
|
-
});
|
|
531
|
-
this.options.cache = true;
|
|
532
|
-
if (ttl)
|
|
533
|
-
this.options.ttl = ttl;
|
|
534
|
-
return this;
|
|
535
|
-
}
|
|
536
|
-
noCache() {
|
|
537
|
-
logger.debug("Disabling cache");
|
|
538
|
-
this.options.cache = false;
|
|
539
|
-
return this;
|
|
540
|
-
}
|
|
541
|
-
bypassCache() {
|
|
542
|
-
logger.debug("Bypassing cache");
|
|
543
|
-
this.options.cache = false;
|
|
544
|
-
this.options.ttl = 0;
|
|
545
|
-
return this;
|
|
546
|
-
}
|
|
547
|
-
toJSON() {
|
|
548
|
-
return {
|
|
549
|
-
model: this.model,
|
|
550
|
-
filters: this.filters,
|
|
551
|
-
includes: this.includes,
|
|
552
|
-
sorting: this.sorting,
|
|
553
|
-
pagination: this.pagination,
|
|
554
|
-
options: this.options
|
|
555
|
-
};
|
|
556
|
-
}
|
|
557
|
-
async get() {
|
|
558
|
-
logger.debug("Starting query:", {
|
|
559
|
-
model: this.model,
|
|
560
|
-
filterCount: this.filters.length,
|
|
561
|
-
includeCount: Object.keys(this.includes).length,
|
|
562
|
-
sortingCount: this.sorting.length,
|
|
563
|
-
pagination: this.pagination,
|
|
564
|
-
options: this.options
|
|
565
|
-
});
|
|
566
|
-
const result = await this.loader.load(this.model);
|
|
567
|
-
const modelConfig = result.model;
|
|
568
|
-
logger.debug("Model loaded:", {
|
|
569
|
-
model: this.model,
|
|
570
|
-
metadata: modelConfig.metadata,
|
|
571
|
-
contentKeys: Object.keys(result.content)
|
|
572
|
-
});
|
|
573
|
-
let data;
|
|
574
|
-
if (modelConfig.metadata.localization) {
|
|
575
|
-
const locale = this.options.locale || "en";
|
|
576
|
-
logger.debug("Selecting content for localized model:", {
|
|
577
|
-
model: this.model,
|
|
578
|
-
requestedLocale: locale,
|
|
579
|
-
availableLocales: Object.keys(result.content)
|
|
580
|
-
});
|
|
581
|
-
data = result.content[locale];
|
|
582
|
-
if (!data) {
|
|
583
|
-
logger.error("Content not found:", {
|
|
584
|
-
model: this.model,
|
|
585
|
-
locale,
|
|
586
|
-
availableLocales: Object.keys(result.content)
|
|
587
|
-
});
|
|
588
|
-
throw new Error(`Content not found for locale: ${locale}`);
|
|
589
|
-
}
|
|
590
|
-
} else {
|
|
591
|
-
logger.debug("Selecting content for non-localized model:", {
|
|
592
|
-
model: this.model,
|
|
593
|
-
contentKeys: Object.keys(result.content)
|
|
594
|
-
});
|
|
595
|
-
if (!result.content.default) {
|
|
596
|
-
logger.error("Content not found:", {
|
|
597
|
-
model: this.model,
|
|
598
|
-
contentKeys: Object.keys(result.content)
|
|
599
|
-
});
|
|
600
|
-
throw new Error(`Content not found for model: ${this.model}`);
|
|
601
|
-
}
|
|
602
|
-
data = result.content.default;
|
|
603
|
-
}
|
|
604
|
-
logger.debug("Executing query:", {
|
|
605
|
-
model: this.model,
|
|
606
|
-
dataLength: data.length
|
|
607
|
-
});
|
|
608
|
-
return this.executor.execute({
|
|
609
|
-
model: this.model,
|
|
610
|
-
data,
|
|
611
|
-
filters: this.filters,
|
|
612
|
-
includes: this.includes,
|
|
613
|
-
sorting: this.sorting,
|
|
614
|
-
pagination: this.pagination,
|
|
615
|
-
options: this.options
|
|
616
|
-
});
|
|
617
|
-
}
|
|
618
|
-
async first() {
|
|
619
|
-
const result = await this.limit(1).get();
|
|
620
|
-
return result.data[0] || null;
|
|
621
|
-
}
|
|
622
|
-
async count() {
|
|
623
|
-
const result = await this.get();
|
|
624
|
-
return result.total;
|
|
625
|
-
}
|
|
626
|
-
};
|
|
627
|
-
__name(_ContentrainQueryBuilder, "ContentrainQueryBuilder");
|
|
628
|
-
var ContentrainQueryBuilder = _ContentrainQueryBuilder;
|
|
629
|
-
|
|
630
|
-
// src/query/executor.ts
|
|
631
|
-
var _QueryExecutor = class _QueryExecutor {
|
|
632
|
-
constructor(loader) {
|
|
633
|
-
this.loader = loader;
|
|
634
|
-
}
|
|
635
|
-
applyFilters(data, filters) {
|
|
636
|
-
logger.debug("Starting to apply filters:", {
|
|
637
|
-
dataLength: data.length,
|
|
638
|
-
filters
|
|
639
|
-
});
|
|
640
|
-
const result = data.filter((item) => {
|
|
641
|
-
return filters.every(({ field, operator, value }) => {
|
|
642
|
-
const itemValue = item[field];
|
|
643
|
-
const validOperators = ["eq", "ne", "gt", "gte", "lt", "lte", "in", "nin", "contains", "startsWith", "endsWith"];
|
|
644
|
-
if (!validOperators.includes(operator)) {
|
|
645
|
-
logger.error("Invalid operator:", operator);
|
|
646
|
-
throw new Error(`Invalid operator: ${operator}`);
|
|
647
|
-
}
|
|
648
|
-
if (typeof itemValue === "string" && typeof value === "string") {
|
|
649
|
-
return this.applyStringOperation(itemValue, operator, value);
|
|
650
|
-
}
|
|
651
|
-
if (Array.isArray(value)) {
|
|
652
|
-
switch (operator) {
|
|
653
|
-
case "in":
|
|
654
|
-
return value.includes(itemValue);
|
|
655
|
-
case "nin":
|
|
656
|
-
return !value.includes(itemValue);
|
|
657
|
-
default:
|
|
658
|
-
logger.error("Invalid array operator:", operator);
|
|
659
|
-
throw new Error(`Invalid array operator: ${operator}`);
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
|
-
if (Array.isArray(itemValue)) {
|
|
663
|
-
switch (operator) {
|
|
664
|
-
case "in":
|
|
665
|
-
return value.some((v) => itemValue.includes(v));
|
|
666
|
-
case "nin":
|
|
667
|
-
return !value.some((v) => itemValue.includes(v));
|
|
668
|
-
default:
|
|
669
|
-
logger.error("Invalid array operator:", operator);
|
|
670
|
-
throw new Error(`Invalid array operator: ${operator}`);
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
if (typeof itemValue === "number" && typeof value === "number") {
|
|
674
|
-
switch (operator) {
|
|
675
|
-
case "eq":
|
|
676
|
-
return itemValue === value;
|
|
677
|
-
case "ne":
|
|
678
|
-
return itemValue !== value;
|
|
679
|
-
case "gt":
|
|
680
|
-
return itemValue > value;
|
|
681
|
-
case "gte":
|
|
682
|
-
return itemValue >= value;
|
|
683
|
-
case "lt":
|
|
684
|
-
return itemValue < value;
|
|
685
|
-
case "lte":
|
|
686
|
-
return itemValue <= value;
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
return false;
|
|
690
|
-
});
|
|
691
|
-
});
|
|
692
|
-
logger.debug("Filter application completed:", {
|
|
693
|
-
initialCount: data.length,
|
|
694
|
-
resultCount: result.length
|
|
695
|
-
});
|
|
696
|
-
return result;
|
|
697
|
-
}
|
|
698
|
-
applySorting(data, sorting) {
|
|
699
|
-
return [...data].sort((a, b) => {
|
|
700
|
-
for (const { field, direction } of sorting) {
|
|
701
|
-
if (!(field in a)) {
|
|
702
|
-
throw new Error(`Invalid sort field: ${field}`);
|
|
703
|
-
}
|
|
704
|
-
const aValue = a[field];
|
|
705
|
-
const bValue = b[field];
|
|
706
|
-
if (aValue === bValue)
|
|
707
|
-
continue;
|
|
708
|
-
const compareResult = aValue < bValue ? -1 : 1;
|
|
709
|
-
return direction === "asc" ? compareResult : -compareResult;
|
|
710
|
-
}
|
|
711
|
-
return 0;
|
|
712
|
-
});
|
|
713
|
-
}
|
|
714
|
-
applyPagination(data, limit, offset = 0) {
|
|
715
|
-
if (!limit)
|
|
716
|
-
return data.slice(offset);
|
|
717
|
-
return data.slice(offset, offset + limit);
|
|
718
|
-
}
|
|
719
|
-
async resolveIncludes(model, data, includes, options) {
|
|
720
|
-
logger.debug("Starting to resolve relations:", {
|
|
721
|
-
model,
|
|
722
|
-
dataLength: data.length,
|
|
723
|
-
includes,
|
|
724
|
-
options
|
|
725
|
-
});
|
|
726
|
-
const result = [...data];
|
|
727
|
-
for (const [field, config] of Object.entries(includes)) {
|
|
728
|
-
logger.debug(`Resolving relation "${field}"`);
|
|
729
|
-
const relations = await this.loader.resolveRelation(
|
|
730
|
-
model,
|
|
731
|
-
field,
|
|
732
|
-
result,
|
|
733
|
-
options.locale
|
|
734
|
-
);
|
|
735
|
-
logger.debug(`Relation "${field}" resolved:`, {
|
|
736
|
-
foundRelationsCount: relations.length
|
|
737
|
-
});
|
|
738
|
-
if (config.include && relations.length) {
|
|
739
|
-
logger.debug(`Resolving nested relations for "${field}":`, config.include);
|
|
740
|
-
await this.resolveIncludes(
|
|
741
|
-
field,
|
|
742
|
-
relations,
|
|
743
|
-
config.include,
|
|
744
|
-
options
|
|
745
|
-
);
|
|
746
|
-
}
|
|
747
|
-
result.forEach((item) => {
|
|
748
|
-
const value = item[field];
|
|
749
|
-
const relatedItems = relations.filter((r) => {
|
|
750
|
-
if (Array.isArray(value)) {
|
|
751
|
-
return value.includes(r.ID);
|
|
752
|
-
}
|
|
753
|
-
return r.ID === value;
|
|
754
|
-
});
|
|
755
|
-
if (!item._relations) {
|
|
756
|
-
item._relations = {};
|
|
757
|
-
}
|
|
758
|
-
item._relations[field] = Array.isArray(value) ? relatedItems : relatedItems[0];
|
|
759
|
-
});
|
|
760
|
-
logger.debug(`Data added for relation "${field}"`);
|
|
761
|
-
}
|
|
762
|
-
return result;
|
|
763
|
-
}
|
|
764
|
-
applyStringOperation(value, operator, searchValue) {
|
|
765
|
-
switch (operator) {
|
|
766
|
-
case "eq":
|
|
767
|
-
return value === searchValue;
|
|
768
|
-
case "ne":
|
|
769
|
-
return value !== searchValue;
|
|
770
|
-
case "contains":
|
|
771
|
-
return value.toLowerCase().includes(searchValue.toLowerCase());
|
|
772
|
-
case "startsWith":
|
|
773
|
-
return value.toLowerCase().startsWith(searchValue.toLowerCase());
|
|
774
|
-
case "endsWith":
|
|
775
|
-
return value.toLowerCase().endsWith(searchValue.toLowerCase());
|
|
776
|
-
default: {
|
|
777
|
-
const _exhaustiveCheck = operator;
|
|
778
|
-
return _exhaustiveCheck;
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
async execute({
|
|
783
|
-
model,
|
|
784
|
-
data,
|
|
785
|
-
filters = [],
|
|
786
|
-
includes = {},
|
|
787
|
-
sorting = [],
|
|
788
|
-
pagination = {},
|
|
789
|
-
options = {}
|
|
790
|
-
}) {
|
|
791
|
-
logger.debug("Starting execution:", {
|
|
792
|
-
model,
|
|
793
|
-
dataLength: data.length,
|
|
794
|
-
filterCount: filters.length,
|
|
795
|
-
includeCount: Object.keys(includes).length,
|
|
796
|
-
sortingCount: sorting.length,
|
|
797
|
-
pagination,
|
|
798
|
-
options
|
|
799
|
-
});
|
|
800
|
-
let result = [...data];
|
|
801
|
-
if (filters.length) {
|
|
802
|
-
logger.debug("Applying filters:", filters);
|
|
803
|
-
result = this.applyFilters(result, filters);
|
|
804
|
-
logger.debug("Remaining items after filtering:", result.length);
|
|
805
|
-
}
|
|
806
|
-
if (Object.keys(includes).length) {
|
|
807
|
-
logger.debug("Resolving relations:", includes);
|
|
808
|
-
result = await this.resolveIncludes(model, result, includes, options);
|
|
809
|
-
logger.debug("Items after relation resolution:", result.length);
|
|
810
|
-
}
|
|
811
|
-
if (sorting.length) {
|
|
812
|
-
logger.debug("Applying sorting:", sorting);
|
|
813
|
-
result = this.applySorting(result, sorting);
|
|
814
|
-
}
|
|
815
|
-
const paginatedData = this.applyPagination(result, pagination.limit, pagination.offset);
|
|
816
|
-
logger.debug("After pagination:", {
|
|
817
|
-
totalCount: result.length,
|
|
818
|
-
pageSize: paginatedData.length,
|
|
819
|
-
offset: pagination.offset || 0,
|
|
820
|
-
hasMore: (pagination.offset || 0) + paginatedData.length < result.length
|
|
821
|
-
});
|
|
822
|
-
return {
|
|
823
|
-
data: paginatedData,
|
|
824
|
-
total: result.length,
|
|
825
|
-
pagination: pagination.limit ? {
|
|
826
|
-
limit: pagination.limit,
|
|
827
|
-
offset: pagination.offset || 0,
|
|
828
|
-
hasMore: (pagination.offset || 0) + paginatedData.length < result.length
|
|
829
|
-
} : undefined
|
|
830
|
-
};
|
|
831
|
-
}
|
|
832
|
-
};
|
|
833
|
-
__name(_QueryExecutor, "QueryExecutor");
|
|
834
|
-
var QueryExecutor = _QueryExecutor;
|
|
835
|
-
|
|
836
|
-
// src/index.ts
|
|
837
|
-
var _ContentrainSDK = class _ContentrainSDK {
|
|
838
|
-
constructor(options) {
|
|
839
|
-
this.loader = new ContentLoader(options);
|
|
840
|
-
this.executor = new QueryExecutor(this.loader);
|
|
841
|
-
}
|
|
842
|
-
query(model) {
|
|
843
|
-
return new ContentrainQueryBuilder(
|
|
844
|
-
model,
|
|
845
|
-
this.executor,
|
|
846
|
-
this.loader
|
|
847
|
-
);
|
|
848
|
-
}
|
|
849
|
-
async load(model) {
|
|
850
|
-
return this.loader.load(model);
|
|
851
|
-
}
|
|
852
|
-
async clearCache() {
|
|
853
|
-
return this.loader.clearCache();
|
|
854
|
-
}
|
|
855
|
-
async refreshCache(model) {
|
|
856
|
-
return this.loader.refreshCache(model);
|
|
857
|
-
}
|
|
858
|
-
getCacheStats() {
|
|
859
|
-
return this.loader.getCacheStats();
|
|
860
|
-
}
|
|
861
|
-
};
|
|
862
|
-
__name(_ContentrainSDK, "ContentrainSDK");
|
|
863
|
-
var ContentrainSDK = _ContentrainSDK;
|
|
864
|
-
|
|
865
|
-
exports.ContentLoader = ContentLoader;
|
|
866
|
-
exports.ContentrainQueryBuilder = ContentrainQueryBuilder;
|
|
867
|
-
exports.ContentrainSDK = ContentrainSDK;
|
|
868
|
-
exports.MemoryCache = MemoryCache;
|
|
869
|
-
exports.QueryExecutor = QueryExecutor;
|
|
870
|
-
exports.logger = logger;
|
|
871
|
-
//# sourceMappingURL=index.js.map
|
|
872
|
-
//# sourceMappingURL=index.js.map
|