@arcaelas/dynamite 1.0.15 → 1.0.17

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.
Files changed (53) hide show
  1. package/package.json +1 -1
  2. package/src/@types/index.d.ts +96 -0
  3. package/src/@types/index.js +9 -0
  4. package/src/core/client.d.ts +69 -0
  5. package/src/core/client.js +164 -0
  6. package/src/core/table.d.ts +98 -0
  7. package/src/core/table.js +459 -0
  8. package/src/core/wrapper.d.ts +17 -0
  9. package/src/core/wrapper.js +46 -0
  10. package/src/decorators/belongs_to.d.ts +1 -0
  11. package/src/decorators/belongs_to.js +24 -0
  12. package/src/decorators/created_at.d.ts +1 -0
  13. package/src/decorators/created_at.js +11 -0
  14. package/src/decorators/default.d.ts +1 -0
  15. package/src/decorators/default.js +47 -0
  16. package/src/decorators/has_many.d.ts +1 -0
  17. package/src/decorators/has_many.js +24 -0
  18. package/src/decorators/index.d.ts +11 -0
  19. package/src/decorators/index.js +36 -0
  20. package/src/decorators/index_sort.d.ts +12 -0
  21. package/src/decorators/index_sort.js +43 -0
  22. package/src/decorators/mutate.d.ts +2 -0
  23. package/src/decorators/mutate.js +51 -0
  24. package/src/decorators/name.d.ts +1 -0
  25. package/src/decorators/name.js +28 -0
  26. package/src/decorators/not_null.d.ts +1 -0
  27. package/src/decorators/not_null.js +13 -0
  28. package/src/decorators/primary_key.d.ts +6 -0
  29. package/src/decorators/primary_key.js +30 -0
  30. package/src/decorators/updated_at.d.ts +12 -0
  31. package/src/decorators/updated_at.js +26 -0
  32. package/src/decorators/validate.d.ts +1 -0
  33. package/src/decorators/validate.js +53 -0
  34. package/src/index.d.ts +22 -0
  35. package/src/index.js +47 -0
  36. package/src/utils/batch-relations.d.ts +14 -0
  37. package/src/utils/batch-relations.js +131 -0
  38. package/src/utils/circular-detector.d.ts +82 -0
  39. package/src/utils/circular-detector.js +212 -0
  40. package/src/utils/memory-manager.d.ts +42 -0
  41. package/src/utils/memory-manager.js +107 -0
  42. package/src/utils/naming.d.ts +8 -0
  43. package/src/utils/naming.js +18 -0
  44. package/src/utils/projection.d.ts +12 -0
  45. package/src/utils/projection.js +51 -0
  46. package/src/utils/relations.d.ts +17 -0
  47. package/src/utils/relations.js +165 -0
  48. package/src/utils/security-validator.d.ts +49 -0
  49. package/src/utils/security-validator.js +163 -0
  50. package/src/utils/throttle-manager.d.ts +78 -0
  51. package/src/utils/throttle-manager.js +201 -0
  52. package/src/utils/transaction-manager.d.ts +88 -0
  53. package/src/utils/transaction-manager.js +300 -0
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ /**
3
+ * @file index.ts
4
+ * @descripcion Decorador @Index para Partition Key
5
+ * @autor Miguel Alejandro
6
+ * @fecha 2025-01-27
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.default = Index;
10
+ const wrapper_1 = require("../core/wrapper");
11
+ const naming_1 = require("../utils/naming");
12
+ /**
13
+ * Decorador para marcar propiedad como Partition Key.
14
+ * Configura la propiedad como índice principal para consultas.
15
+ */
16
+ function Index() {
17
+ return (target, prop) => {
18
+ const ctor = target.constructor;
19
+ const tableName = (0, naming_1.toSnakePlural)(ctor.name);
20
+ const entry = (0, wrapper_1.ensureConfig)(ctor, tableName);
21
+ // Verificar si ya existe un índice primario
22
+ const existingIndex = [...entry.columns.values()].find((col) => col.index === true);
23
+ if (existingIndex && existingIndex.name !== String(prop)) {
24
+ throw new Error(`La tabla ${tableName} ya tiene definida una PartitionKey (${existingIndex.name}). ` +
25
+ `No se puede definir otra PartitionKey en '${String(prop)}'`);
26
+ }
27
+ // Obtener o crear la columna y marcar como índice
28
+ const column = (0, wrapper_1.ensureColumn)(entry, prop, String(prop));
29
+ column.index = true;
30
+ // Asegurar que la columna no sea nula por defecto
31
+ if (column.nullable === undefined) {
32
+ column.nullable = false;
33
+ }
34
+ };
35
+ }
36
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @file index_sort.ts
3
+ * @descripcion Decorador @IndexSort para Sort Key
4
+ * @autor Miguel Alejandro
5
+ * @fecha 2025-01-27
6
+ */
7
+ /**
8
+ * Decorador para marcar propiedad como Sort Key.
9
+ * Configura la propiedad como clave de ordenación para consultas.
10
+ * Requiere que exista una PartitionKey (@Index) definida previamente.
11
+ */
12
+ export default function IndexSort(): PropertyDecorator;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ /**
3
+ * @file index_sort.ts
4
+ * @descripcion Decorador @IndexSort para Sort Key
5
+ * @autor Miguel Alejandro
6
+ * @fecha 2025-01-27
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.default = IndexSort;
10
+ const wrapper_1 = require("../core/wrapper");
11
+ const naming_1 = require("../utils/naming");
12
+ /**
13
+ * Decorador para marcar propiedad como Sort Key.
14
+ * Configura la propiedad como clave de ordenación para consultas.
15
+ * Requiere que exista una PartitionKey (@Index) definida previamente.
16
+ */
17
+ function IndexSort() {
18
+ return (target, prop) => {
19
+ const ctor = target.constructor;
20
+ const tableName = (0, naming_1.toSnakePlural)(ctor.name);
21
+ const entry = (0, wrapper_1.ensureConfig)(ctor, tableName);
22
+ // Verificar que exista una PartitionKey definida
23
+ const hasPartitionKey = [...entry.columns.values()].some((col) => col.index === true);
24
+ if (!hasPartitionKey) {
25
+ throw new Error(`No se puede definir una SortKey en '${String(prop)}' sin una PartitionKey. ` +
26
+ `Asegúrate de marcar una propiedad con @Index primero.`);
27
+ }
28
+ // Verificar si ya existe una SortKey
29
+ const existingSortKey = [...entry.columns.values()].find((col) => col.indexSort === true);
30
+ if (existingSortKey && existingSortKey.name !== String(prop)) {
31
+ throw new Error(`La tabla ${tableName} ya tiene una SortKey definida (${existingSortKey.name}). ` +
32
+ `No se puede definir otra SortKey en '${String(prop)}'`);
33
+ }
34
+ // Obtener o crear la columna y marcar como índice de ordenación
35
+ const column = (0, wrapper_1.ensureColumn)(entry, prop, String(prop));
36
+ column.indexSort = true;
37
+ // Asegurar que la columna no sea nula por defecto
38
+ if (column.nullable === undefined) {
39
+ column.nullable = false;
40
+ }
41
+ };
42
+ }
43
+ //# sourceMappingURL=index_sort.js.map
@@ -0,0 +1,2 @@
1
+ import type { Mutate } from "../core/wrapper";
2
+ export default function Mutate(fn: Mutate): PropertyDecorator;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = Mutate;
4
+ const wrapper_1 = require("../core/wrapper");
5
+ const naming_1 = require("../utils/naming");
6
+ function Mutate(fn) {
7
+ if (typeof fn !== "function")
8
+ throw new TypeError("@Mutate requiere función");
9
+ return (target, prop) => {
10
+ const ctor = target.constructor;
11
+ const entry = (0, wrapper_1.ensureConfig)(ctor, (0, naming_1.toSnakePlural)(ctor.name));
12
+ const col = (0, wrapper_1.ensureColumn)(entry, prop, String(prop));
13
+ col.mutate ??= [];
14
+ col.mutate.push(fn);
15
+ !Object.getOwnPropertyDescriptor(ctor.prototype, prop)?.set &&
16
+ defineVirtual(ctor.prototype, col, prop);
17
+ };
18
+ }
19
+ /** Define propiedad virtual con getter/setter para manejo de mutaciones */
20
+ function defineVirtual(proto, col, prop) {
21
+ Object.defineProperty(proto, prop, {
22
+ get() {
23
+ return (this[wrapper_1.STORE] ?? {})[prop];
24
+ },
25
+ set(val) {
26
+ const buf = (this[wrapper_1.STORE] ??= {});
27
+ val =
28
+ val === undefined && col.default !== undefined
29
+ ? typeof col.default === "function"
30
+ ? col.default()
31
+ : col.default
32
+ : val;
33
+ if (col.mutate)
34
+ for (const m of col.mutate)
35
+ val = m(val);
36
+ if (col.validate) {
37
+ for (const v of col.validate) {
38
+ const r = v(val);
39
+ r !== true &&
40
+ (() => {
41
+ throw new Error(typeof r === "string" ? r : "Validación fallida");
42
+ })();
43
+ }
44
+ }
45
+ buf[prop] = val;
46
+ },
47
+ enumerable: true,
48
+ configurable: true,
49
+ });
50
+ }
51
+ //# sourceMappingURL=mutate.js.map
@@ -0,0 +1 @@
1
+ export default function Name(label: string): ClassDecorator & PropertyDecorator;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = Name;
4
+ const wrapper_1 = require("../core/wrapper");
5
+ const naming_1 = require("../utils/naming");
6
+ function Name(label) {
7
+ if (!label || typeof label !== "string")
8
+ throw new TypeError("@Name requiere una cadena no vacía");
9
+ return (target, prop) => {
10
+ const ctor = prop === undefined ? target : target.constructor;
11
+ const entry = (0, wrapper_1.ensureConfig)(ctor, (0, naming_1.toSnakePlural)(ctor.name));
12
+ if (prop === undefined) {
13
+ const auto = (0, naming_1.toSnakePlural)(ctor.name);
14
+ if (entry.name !== auto && entry.name !== label && entry.name) {
15
+ throw new Error(`La clase ${ctor.name} ya tiene un @Name distinto (${entry.name})`);
16
+ }
17
+ entry.name = label;
18
+ }
19
+ else {
20
+ const col = (0, wrapper_1.ensureColumn)(entry, prop, label);
21
+ if (col.name && col.name !== label) {
22
+ throw new Error(`La columna '${String(prop)}' ya tiene @Name distinto (${col.name})`);
23
+ }
24
+ col.name = label;
25
+ }
26
+ };
27
+ }
28
+ //# sourceMappingURL=name.js.map
@@ -0,0 +1 @@
1
+ export default function NotNull(): PropertyDecorator;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.default = NotNull;
7
+ const validate_1 = __importDefault(require("./validate"));
8
+ function NotNull() {
9
+ return validate_1.default((value) => value !== null &&
10
+ value !== undefined &&
11
+ (typeof value !== "string" || value.trim() !== ""));
12
+ }
13
+ //# sourceMappingURL=not_null.js.map
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Decorador para marcar una propiedad como clave primaria.
3
+ * Aplica automáticamente @Index y @IndexSort y marca el campo como primaryKey en los metadatos.
4
+ * @param name - Nombre opcional para el índice (no utilizado actualmente, mantenido por compatibilidad)
5
+ */
6
+ export default function PrimaryKey(name?: string): PropertyDecorator;
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.default = PrimaryKey;
7
+ const wrapper_1 = require("../core/wrapper");
8
+ const naming_1 = require("../utils/naming");
9
+ const index_1 = __importDefault(require("./index"));
10
+ const index_sort_1 = __importDefault(require("./index_sort"));
11
+ /**
12
+ * Decorador para marcar una propiedad como clave primaria.
13
+ * Aplica automáticamente @Index y @IndexSort y marca el campo como primaryKey en los metadatos.
14
+ * @param name - Nombre opcional para el índice (no utilizado actualmente, mantenido por compatibilidad)
15
+ */
16
+ function PrimaryKey(name = "primary") {
17
+ return (target, prop) => {
18
+ // Aplicar decoradores de índice
19
+ (0, index_1.default)()(target, prop);
20
+ (0, index_sort_1.default)()(target, prop);
21
+ // Marcar explícitamente como clave primaria en los metadatos
22
+ const ctor = target.constructor;
23
+ const entry = (0, wrapper_1.ensureConfig)(ctor, (0, naming_1.toSnakePlural)(ctor.name));
24
+ const column = (0, wrapper_1.ensureColumn)(entry, prop, String(prop));
25
+ // Establecer metadatos adicionales para clave primaria
26
+ column.primaryKey = true;
27
+ column.nullable = false; // Las claves primarias no pueden ser nulas
28
+ };
29
+ }
30
+ //# sourceMappingURL=primary_key.js.map
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Decorador que marca una propiedad para que se actualice automáticamente con la fecha/hora actual
3
+ * cada vez que se guarde el modelo.
4
+ *
5
+ * @example
6
+ * class User extends Table<User> {
7
+ * @PrimaryKey() id: string;
8
+ * name: string;
9
+ * @UpdatedAt() updated_at: string;
10
+ * }
11
+ */
12
+ export default function UpdatedAt(): (target: any, propertyKey: string | symbol) => void;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = UpdatedAt;
4
+ const wrapper_1 = require("../core/wrapper");
5
+ /**
6
+ * Decorador que marca una propiedad para que se actualice automáticamente con la fecha/hora actual
7
+ * cada vez que se guarde el modelo.
8
+ *
9
+ * @example
10
+ * class User extends Table<User> {
11
+ * @PrimaryKey() id: string;
12
+ * name: string;
13
+ * @UpdatedAt() updated_at: string;
14
+ * }
15
+ */
16
+ function UpdatedAt() {
17
+ return function (target, propertyKey) {
18
+ const ctor = target.constructor;
19
+ const entry = (0, wrapper_1.ensureConfig)(ctor, ctor.name);
20
+ const column = (0, wrapper_1.ensureColumn)(entry, propertyKey, propertyKey);
21
+ // Marcamos la columna como updatedAt para que se actualice automáticamente al guardar
22
+ column.updatedAt = true;
23
+ // No establecemos un valor por defecto aquí, se establecerá en el método save()
24
+ };
25
+ }
26
+ //# sourceMappingURL=updated_at.js.map
@@ -0,0 +1 @@
1
+ export default function Validate(validators: ((v: unknown) => true | string) | ((v: unknown) => true | string)[]): PropertyDecorator;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = Validate;
4
+ const wrapper_1 = require("../core/wrapper");
5
+ const naming_1 = require("../utils/naming");
6
+ function Validate(validators) {
7
+ const list = Array.isArray(validators) ? validators : [validators];
8
+ if (!list.length || list.some((v) => typeof v !== "function")) {
9
+ throw new TypeError("@Validate requiere funciones");
10
+ }
11
+ return (target, prop) => {
12
+ const ctor = target.constructor;
13
+ const entry = (0, wrapper_1.ensureConfig)(ctor, (0, naming_1.toSnakePlural)(ctor.name));
14
+ const col = (0, wrapper_1.ensureColumn)(entry, prop, String(prop));
15
+ col.validate ??= [];
16
+ col.validate.push(...list);
17
+ !Object.getOwnPropertyDescriptor(ctor.prototype, prop)?.set &&
18
+ defineVirtual(ctor.prototype, col, prop);
19
+ };
20
+ }
21
+ /** Define propiedad virtual con getter/setter para manejo de validaciones */
22
+ function defineVirtual(proto, col, prop) {
23
+ Object.defineProperty(proto, prop, {
24
+ get() {
25
+ return (this[wrapper_1.STORE] ?? {})[prop];
26
+ },
27
+ set(val) {
28
+ const buf = (this[wrapper_1.STORE] ??= {});
29
+ val =
30
+ val === undefined && col.default !== undefined
31
+ ? typeof col.default === "function"
32
+ ? col.default()
33
+ : col.default
34
+ : val;
35
+ if (col.mutate)
36
+ for (const m of col.mutate)
37
+ val = m(val);
38
+ if (col.validate) {
39
+ for (const v of col.validate) {
40
+ const r = v(val);
41
+ r !== true &&
42
+ (() => {
43
+ throw new Error(typeof r === "string" ? r : "Validación fallida");
44
+ })();
45
+ }
46
+ }
47
+ buf[prop] = val;
48
+ },
49
+ enumerable: true,
50
+ configurable: true,
51
+ });
52
+ }
53
+ //# sourceMappingURL=validate.js.map
package/src/index.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @file index.ts
3
+ * @descripcion Punto de entrada público de la librería
4
+ * @autor Miguel Alejandro
5
+ * @fecha 2025-08-07
6
+ */
7
+ export { Dynamite } from "./core/client";
8
+ export { default as Table } from "./core/table";
9
+ export { default as BelongsTo } from "./decorators/belongs_to";
10
+ export { default as CreatedAt } from "./decorators/created_at";
11
+ export { default as Default } from "./decorators/default";
12
+ export { default as HasMany } from "./decorators/has_many";
13
+ export { default as Index } from "./decorators/index";
14
+ export { default as IndexSort } from "./decorators/index_sort";
15
+ export { default as Mutate } from "./decorators/mutate";
16
+ export { default as Name } from "./decorators/name";
17
+ export { default as NotNull } from "./decorators/not_null";
18
+ export { default as PrimaryKey } from "./decorators/primary_key";
19
+ export { default as UpdatedAt } from "./decorators/updated_at";
20
+ export { default as Validate } from "./decorators/validate";
21
+ export { belongsTo, hasMany } from "./utils/relations";
22
+ export type { BelongsTo as BelongsToType, CreationOptional, FilterableAttributes, HasMany as HasManyType, InferAttributes, NonAttribute, QueryOperator, QueryResult, WhereOptions, WhereOptionsWithoutWhere, } from "./@types/index";
package/src/index.js ADDED
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ /**
3
+ * @file index.ts
4
+ * @descripcion Punto de entrada público de la librería
5
+ * @autor Miguel Alejandro
6
+ * @fecha 2025-08-07
7
+ */
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.hasMany = exports.belongsTo = exports.Validate = exports.UpdatedAt = exports.PrimaryKey = exports.NotNull = exports.Name = exports.Mutate = exports.IndexSort = exports.Index = exports.HasMany = exports.Default = exports.CreatedAt = exports.BelongsTo = exports.Table = exports.Dynamite = void 0;
13
+ // Clases núcleo
14
+ var client_1 = require("./core/client");
15
+ Object.defineProperty(exports, "Dynamite", { enumerable: true, get: function () { return client_1.Dynamite; } });
16
+ var table_1 = require("./core/table");
17
+ Object.defineProperty(exports, "Table", { enumerable: true, get: function () { return __importDefault(table_1).default; } });
18
+ // Decoradores
19
+ var belongs_to_1 = require("./decorators/belongs_to");
20
+ Object.defineProperty(exports, "BelongsTo", { enumerable: true, get: function () { return __importDefault(belongs_to_1).default; } });
21
+ var created_at_1 = require("./decorators/created_at");
22
+ Object.defineProperty(exports, "CreatedAt", { enumerable: true, get: function () { return __importDefault(created_at_1).default; } });
23
+ var default_1 = require("./decorators/default");
24
+ Object.defineProperty(exports, "Default", { enumerable: true, get: function () { return __importDefault(default_1).default; } });
25
+ var has_many_1 = require("./decorators/has_many");
26
+ Object.defineProperty(exports, "HasMany", { enumerable: true, get: function () { return __importDefault(has_many_1).default; } });
27
+ var index_1 = require("./decorators/index");
28
+ Object.defineProperty(exports, "Index", { enumerable: true, get: function () { return __importDefault(index_1).default; } });
29
+ var index_sort_1 = require("./decorators/index_sort");
30
+ Object.defineProperty(exports, "IndexSort", { enumerable: true, get: function () { return __importDefault(index_sort_1).default; } });
31
+ var mutate_1 = require("./decorators/mutate");
32
+ Object.defineProperty(exports, "Mutate", { enumerable: true, get: function () { return __importDefault(mutate_1).default; } });
33
+ var name_1 = require("./decorators/name");
34
+ Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return __importDefault(name_1).default; } });
35
+ var not_null_1 = require("./decorators/not_null");
36
+ Object.defineProperty(exports, "NotNull", { enumerable: true, get: function () { return __importDefault(not_null_1).default; } });
37
+ var primary_key_1 = require("./decorators/primary_key");
38
+ Object.defineProperty(exports, "PrimaryKey", { enumerable: true, get: function () { return __importDefault(primary_key_1).default; } });
39
+ var updated_at_1 = require("./decorators/updated_at");
40
+ Object.defineProperty(exports, "UpdatedAt", { enumerable: true, get: function () { return __importDefault(updated_at_1).default; } });
41
+ var validate_1 = require("./decorators/validate");
42
+ Object.defineProperty(exports, "Validate", { enumerable: true, get: function () { return __importDefault(validate_1).default; } });
43
+ // Relaciones
44
+ var relations_1 = require("./utils/relations");
45
+ Object.defineProperty(exports, "belongsTo", { enumerable: true, get: function () { return relations_1.belongsTo; } });
46
+ Object.defineProperty(exports, "hasMany", { enumerable: true, get: function () { return relations_1.hasMany; } });
47
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @file batch-relations.ts
3
+ * @description Optimized batch loading for relations
4
+ * @autor Miguel Alejandro
5
+ * @fecha 2025-01-27
6
+ */
7
+ /** Batch loader para hasMany relations */
8
+ export declare const batchLoadHasMany: (Model: any, parentItems: any[], relation: any) => Promise<Map<any, any>>;
9
+ /** Batch loader para belongsTo relations con cache */
10
+ export declare const batchLoadBelongsTo: (Model: any, parentItems: any[], relation: any) => Promise<Map<any, any>>;
11
+ /** Optimized processIncludes con batch loading */
12
+ export declare const processIncludesBatch: (Model: any, items: any[], include: any, depth?: number) => Promise<any[]>;
13
+ /** Clear expired cache entries */
14
+ export declare const cleanupRelationCache: () => void;
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ /**
3
+ * @file batch-relations.ts
4
+ * @description Optimized batch loading for relations
5
+ * @autor Miguel Alejandro
6
+ * @fecha 2025-01-27
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.cleanupRelationCache = exports.processIncludesBatch = exports.batchLoadBelongsTo = exports.batchLoadHasMany = void 0;
10
+ const wrapper_1 = require("../core/wrapper");
11
+ /** Cache multi-nivel con TTL */
12
+ const relCache = new Map();
13
+ /** Batch loader para hasMany relations */
14
+ const batchLoadHasMany = async (Model, parentItems, relation) => {
15
+ const { targetModel, foreignKey, localKey } = relation;
16
+ const TargetModel = targetModel();
17
+ // Agrupar claves para batch query
18
+ const parentKeys = parentItems.map((item) => item[localKey]).filter(Boolean);
19
+ if (!parentKeys.length)
20
+ return new Map();
21
+ // Single query con 'in' operator
22
+ const relatedItems = await TargetModel.where({
23
+ [foreignKey]: { in: parentKeys },
24
+ });
25
+ // Group by foreign key
26
+ const grouped = new Map();
27
+ relatedItems.forEach((item) => {
28
+ const key = item[foreignKey];
29
+ if (!grouped.has(key))
30
+ grouped.set(key, []);
31
+ grouped.get(key).push(item);
32
+ });
33
+ return grouped;
34
+ };
35
+ exports.batchLoadHasMany = batchLoadHasMany;
36
+ /** Batch loader para belongsTo relations con cache */
37
+ const batchLoadBelongsTo = async (Model, parentItems, relation) => {
38
+ const { targetModel, localKey, foreignKey } = relation;
39
+ const TargetModel = targetModel();
40
+ const cacheKey = `${TargetModel.name}_belongsTo`;
41
+ // Verificar cache existente
42
+ const cache = relCache.get(cacheKey) || new Map();
43
+ relCache.set(cacheKey, cache);
44
+ const now = Date.now();
45
+ // Separar keys en cache vs no-cache
46
+ const keysToFetch = [];
47
+ const cachedResults = new Map();
48
+ parentItems.forEach((item) => {
49
+ const key = item[localKey];
50
+ if (!key)
51
+ return;
52
+ const cached = cache.get(key);
53
+ if (cached && cached.expires > now) {
54
+ cachedResults.set(key, cached.data);
55
+ }
56
+ else {
57
+ keysToFetch.push(key);
58
+ }
59
+ });
60
+ // Fetch missing items
61
+ if (keysToFetch.length) {
62
+ const fetchedItems = await TargetModel.where({
63
+ [foreignKey]: { in: keysToFetch },
64
+ });
65
+ // Update cache (5min TTL)
66
+ const expires = now + 300000;
67
+ fetchedItems.forEach((item) => {
68
+ const key = item[foreignKey];
69
+ cache.set(key, { data: item, expires });
70
+ cachedResults.set(key, item);
71
+ });
72
+ }
73
+ return cachedResults;
74
+ };
75
+ exports.batchLoadBelongsTo = batchLoadBelongsTo;
76
+ /** Optimized processIncludes con batch loading */
77
+ const processIncludesBatch = async (Model, items, include, depth = 0) => {
78
+ if (!include || depth > 10 || !items.length)
79
+ return items;
80
+ const meta = (0, wrapper_1.mustMeta)(Model);
81
+ // Process all relations in parallel
82
+ const relationPromises = Object.entries(include).map(async ([relationKey, relationOptions]) => {
83
+ const relation = meta.relations.get(relationKey);
84
+ if (!relation)
85
+ return;
86
+ let relatedData;
87
+ // Use batch loading based on relation type
88
+ if (relation.type === "hasMany") {
89
+ relatedData = await (0, exports.batchLoadHasMany)(Model, items, relation);
90
+ }
91
+ else {
92
+ relatedData = await (0, exports.batchLoadBelongsTo)(Model, items, relation);
93
+ }
94
+ // Assign relations to items
95
+ items.forEach((item) => {
96
+ const key = item[relation.localKey];
97
+ const related = relatedData.get(key);
98
+ if (relation.type === "hasMany") {
99
+ item[relationKey] = related || [];
100
+ }
101
+ else {
102
+ item[relationKey] = related || null;
103
+ }
104
+ });
105
+ // Recursive processing for nested includes
106
+ if (relationOptions?.include && relatedData.size) {
107
+ const allRelated = Array.from(relatedData.values()).flat();
108
+ const TargetModel = relation.targetModel();
109
+ await (0, exports.processIncludesBatch)(TargetModel, allRelated, relationOptions.include, depth + 1);
110
+ }
111
+ });
112
+ await Promise.all(relationPromises);
113
+ return items;
114
+ };
115
+ exports.processIncludesBatch = processIncludesBatch;
116
+ /** Clear expired cache entries */
117
+ const cleanupRelationCache = () => {
118
+ const now = Date.now();
119
+ relCache.forEach((cache, modelKey) => {
120
+ cache.forEach((entry, key) => {
121
+ if (entry.expires <= now)
122
+ cache.delete(key);
123
+ });
124
+ if (cache.size === 0)
125
+ relCache.delete(modelKey);
126
+ });
127
+ };
128
+ exports.cleanupRelationCache = cleanupRelationCache;
129
+ // Auto cleanup every 5 minutes
130
+ setInterval(exports.cleanupRelationCache, 300000);
131
+ //# sourceMappingURL=batch-relations.js.map
@@ -0,0 +1,82 @@
1
+ /**
2
+ * @file circular-detector.ts
3
+ * @description Detection and prevention of circular references in relations
4
+ * @author Miguel Alejandro
5
+ * @fecha 2025-08-31
6
+ */
7
+ interface TraversalPath {
8
+ modelName: string;
9
+ relationKey: string;
10
+ depth: number;
11
+ }
12
+ interface CircularDetectionConfig {
13
+ maxDepth: number;
14
+ maxIncludeDepth: number;
15
+ trackingEnabled: boolean;
16
+ }
17
+ declare class CircularReferenceDetector {
18
+ private static readonly DEFAULT_CONFIG;
19
+ private config;
20
+ private activePaths;
21
+ private pathHistory;
22
+ constructor(config?: Partial<CircularDetectionConfig>);
23
+ /**
24
+ * Verificar si una ruta de inclusión es segura
25
+ */
26
+ validateIncludePath(modelName: string, includeOptions: any, currentDepth?: number, visitedModels?: Set<string>): void;
27
+ /**
28
+ * Validar estructura de relaciones en tiempo de definición
29
+ */
30
+ validateRelationStructure(models: Map<string, any>, maxAllowedCycles?: number): ValidationResult;
31
+ /**
32
+ * Construir grafo de relaciones
33
+ */
34
+ private buildRelationGraph;
35
+ /**
36
+ * Detectar ciclos usando DFS
37
+ */
38
+ private detectCycles;
39
+ /**
40
+ * Generar sugerencias para resolver ciclos
41
+ */
42
+ private generateSuggestions;
43
+ /**
44
+ * Inferir nombre del modelo target (simplificado)
45
+ */
46
+ private inferTargetModelName;
47
+ /**
48
+ * Crear contexto de rastreo para includes anidados
49
+ */
50
+ createTrackingContext(): CircularTracker;
51
+ /**
52
+ * Obtener historial de paths para debugging
53
+ */
54
+ getPathHistory(): TraversalPath[];
55
+ /**
56
+ * Limpiar historial
57
+ */
58
+ clearHistory(): void;
59
+ }
60
+ /**
61
+ * Tracker específico para una operación de include
62
+ */
63
+ declare class CircularTracker {
64
+ private visitedModels;
65
+ private currentPath;
66
+ private maxDepth;
67
+ constructor(maxDepth: number);
68
+ enter(modelName: string): void;
69
+ exit(modelName: string): void;
70
+ getCurrentPath(): string[];
71
+ }
72
+ interface ValidationResult {
73
+ isValid: boolean;
74
+ cycles: string[][];
75
+ suggestions: string[];
76
+ }
77
+ declare class CircularReferenceError extends Error {
78
+ constructor(message: string);
79
+ }
80
+ declare const circularDetector: CircularReferenceDetector;
81
+ export { CircularReferenceDetector, CircularReferenceError, CircularTracker, ValidationResult, circularDetector, };
82
+ export default circularDetector;