@jmlq/logger 0.1.0-alpha.7 → 0.1.0-alpha.8

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 (145) hide show
  1. package/README.md +225 -733
  2. package/dist/examples/data-source-service.example.d.ts +3 -0
  3. package/dist/examples/data-source-service.example.js +174 -0
  4. package/dist/examples/flush-buffers-use-case.example.d.ts +3 -0
  5. package/dist/examples/flush-buffers-use-case.example.js +60 -0
  6. package/dist/examples/get-logs-use-case.example.d.ts +3 -0
  7. package/dist/examples/get-logs-use-case.example.js +110 -0
  8. package/dist/examples/index.example.d.ts +8 -0
  9. package/dist/examples/index.example.js +116 -0
  10. package/dist/examples/logger-factory.example.d.ts +39 -0
  11. package/dist/examples/logger-factory.example.js +158 -0
  12. package/dist/examples/normalize-message.example.d.ts +3 -0
  13. package/dist/examples/normalize-message.example.js +80 -0
  14. package/dist/examples/pii-redactor.example.d.ts +3 -0
  15. package/dist/examples/pii-redactor.example.js +129 -0
  16. package/dist/examples/save-log-use-case.example.d.ts +3 -0
  17. package/dist/examples/save-log-use-case.example.js +150 -0
  18. package/dist/examples/to-log-level.example.d.ts +3 -0
  19. package/dist/examples/to-log-level.example.js +49 -0
  20. package/dist/examples/to-pii-regex.example.d.ts +3 -0
  21. package/dist/examples/to-pii-regex.example.js +75 -0
  22. package/dist/{presentation → src/application}/factory/create-logger.d.ts +1 -1
  23. package/dist/{presentation → src/application}/factory/create-logger.js +3 -3
  24. package/dist/src/application/factory/index.d.ts +1 -0
  25. package/dist/{presentation → src/application}/factory/index.js +1 -1
  26. package/dist/src/application/factory/logger.factory.d.ts +12 -0
  27. package/dist/src/application/factory/logger.factory.js +74 -0
  28. package/dist/src/application/index.d.ts +2 -0
  29. package/dist/src/application/index.js +18 -0
  30. package/dist/src/application/use-cases/flush-buffers.use-case.d.ts +6 -0
  31. package/dist/{application/use-cases/flush-buffers.js → src/application/use-cases/flush-buffers.use-case.js} +3 -3
  32. package/dist/src/application/use-cases/get-logs.use-case.d.ts +8 -0
  33. package/dist/{application/use-cases/get-logs.js → src/application/use-cases/get-logs.use-case.js} +3 -3
  34. package/dist/src/application/use-cases/index.d.ts +3 -0
  35. package/dist/{application → src/application}/use-cases/index.js +3 -3
  36. package/dist/src/application/use-cases/save-log.use-case.d.ts +8 -0
  37. package/dist/src/application/use-cases/save-log.use-case.js +26 -0
  38. package/dist/src/domain/index.d.ts +6 -0
  39. package/dist/src/domain/index.js +22 -0
  40. package/dist/src/domain/ports/create-logger-options.port.d.ts +7 -0
  41. package/dist/src/domain/ports/index.d.ts +6 -0
  42. package/dist/src/domain/ports/index.js +22 -0
  43. package/dist/src/domain/ports/log-datasource.port.d.ts +9 -0
  44. package/dist/src/domain/ports/logger-factory-config.port.d.ts +28 -0
  45. package/dist/src/domain/ports/logger-service.port.d.ts +19 -0
  46. package/dist/{domain/contracts/logger.d.ts → src/domain/ports/logger.port.d.ts} +0 -9
  47. package/dist/src/domain/ports/logger.port.js +2 -0
  48. package/dist/src/domain/ports/pii-redactor.port.d.ts +5 -0
  49. package/dist/src/domain/ports/pii-redactor.port.js +2 -0
  50. package/dist/src/domain/request/get-logs-filter.props.d.ts +9 -0
  51. package/dist/src/domain/request/get-logs-filter.props.js +2 -0
  52. package/dist/src/domain/request/index.d.ts +5 -0
  53. package/dist/src/domain/request/index.js +21 -0
  54. package/dist/src/domain/request/log.props.d.ts +7 -0
  55. package/dist/src/domain/request/log.props.js +2 -0
  56. package/dist/src/domain/request/pii-options.props.d.ts +8 -0
  57. package/dist/src/domain/request/pii-options.props.js +2 -0
  58. package/dist/src/domain/request/pii-replacement.props.d.ts +5 -0
  59. package/dist/src/domain/request/pii-replacement.props.js +2 -0
  60. package/dist/src/domain/request/save-log.props.d.ts +7 -0
  61. package/dist/src/domain/request/save-log.props.js +2 -0
  62. package/dist/src/domain/response/index.d.ts +1 -0
  63. package/dist/{domain/value-objects → src/domain/response}/index.js +1 -1
  64. package/dist/src/domain/response/log.response.d.ts +7 -0
  65. package/dist/src/domain/response/log.response.js +2 -0
  66. package/dist/src/domain/services/index.d.ts +4 -0
  67. package/dist/{domain/contracts → src/domain/services}/index.js +4 -3
  68. package/dist/src/domain/services/log-level.service.d.ts +2 -0
  69. package/dist/src/domain/services/log-level.service.js +27 -0
  70. package/dist/src/domain/services/message-normalizer.service.d.ts +3 -0
  71. package/dist/src/domain/services/message-normalizer.service.js +8 -0
  72. package/dist/src/domain/services/pii-pattern.service.d.ts +2 -0
  73. package/dist/src/domain/services/pii-pattern.service.js +13 -0
  74. package/dist/src/domain/services/pii-redactor.d.ts +10 -0
  75. package/dist/{domain → src/domain}/services/pii-redactor.js +8 -17
  76. package/dist/src/domain/services/pii-redactor.service.d.ts +10 -0
  77. package/dist/src/domain/services/pii-redactor.service.js +68 -0
  78. package/dist/src/domain/types/index.d.ts +1 -0
  79. package/dist/src/domain/types/index.js +17 -0
  80. package/dist/src/domain/types/log-message.type.d.ts +1 -0
  81. package/dist/src/domain/types/log-message.type.js +2 -0
  82. package/dist/src/domain/value-objects/index.d.ts +1 -0
  83. package/dist/{domain/services → src/domain/value-objects}/index.js +1 -1
  84. package/dist/{domain/value-objects/log-level.d.ts → src/domain/value-objects/log-level.vo.d.ts} +0 -1
  85. package/dist/src/domain/value-objects/log-level.vo.js +13 -0
  86. package/dist/src/index.d.ts +6 -0
  87. package/dist/src/index.js +22 -0
  88. package/dist/src/infrastructure/datasources/in-memory-log.datasource.d.ts +1 -0
  89. package/dist/src/infrastructure/datasources/in-memory-log.datasource.js +2 -0
  90. package/dist/src/infrastructure/datasources/index.d.ts +1 -0
  91. package/dist/{infrastructure/adapters → src/infrastructure/datasources}/index.js +1 -1
  92. package/dist/src/infrastructure/index.d.ts +1 -0
  93. package/dist/{domain/types → src/infrastructure}/index.js +1 -1
  94. package/dist/src/infrastructure/services/data-source-error-handler.type.d.ts +5 -0
  95. package/dist/src/infrastructure/services/data-source-error-handler.type.js +2 -0
  96. package/dist/src/infrastructure/services/datasource.service.d.ts +15 -0
  97. package/dist/src/infrastructure/services/datasource.service.js +63 -0
  98. package/dist/src/infrastructure/services/index.d.ts +2 -0
  99. package/dist/src/infrastructure/services/index.js +18 -0
  100. package/dist/tests/application/factory/logger-factory.spec.d.ts +1 -0
  101. package/dist/tests/application/factory/logger-factory.spec.js +161 -0
  102. package/dist/tests/application/use-cases/flush-buffers.use-case.spec.d.ts +1 -0
  103. package/dist/tests/application/use-cases/flush-buffers.use-case.spec.js +38 -0
  104. package/dist/tests/application/use-cases/get-logs.use-case.spec.d.ts +1 -0
  105. package/dist/tests/application/use-cases/get-logs.use-case.spec.js +114 -0
  106. package/dist/tests/application/use-cases/save-log.use-case.spec.d.ts +1 -0
  107. package/dist/tests/application/use-cases/save-log.use-case.spec.js +138 -0
  108. package/dist/tests/domain/services/log-level.service.spec.d.ts +1 -0
  109. package/dist/tests/domain/services/log-level.service.spec.js +68 -0
  110. package/dist/tests/domain/services/normalize-message.spec.d.ts +1 -0
  111. package/dist/tests/domain/services/normalize-message.spec.js +83 -0
  112. package/dist/tests/domain/services/pii-redactor.spec.d.ts +1 -0
  113. package/dist/tests/domain/services/pii-redactor.spec.js +170 -0
  114. package/dist/tests/domain/services/to-pii-regex.spec.d.ts +1 -0
  115. package/dist/tests/domain/services/to-pii-regex.spec.js +82 -0
  116. package/dist/tests/infrastructure/services/datasource.service.spec.d.ts +1 -0
  117. package/dist/tests/infrastructure/services/datasource.service.spec.js +128 -0
  118. package/dist/tests/test-utils/create-pii-redactor-mock.d.ts +5 -0
  119. package/dist/tests/test-utils/create-pii-redactor-mock.js +10 -0
  120. package/package.json +27 -19
  121. package/LICENSE +0 -21
  122. package/dist/application/use-cases/flush-buffers.d.ts +0 -6
  123. package/dist/application/use-cases/get-logs.d.ts +0 -7
  124. package/dist/application/use-cases/index.d.ts +0 -3
  125. package/dist/application/use-cases/save-log.d.ts +0 -13
  126. package/dist/application/use-cases/save-log.js +0 -30
  127. package/dist/domain/contracts/index.d.ts +0 -3
  128. package/dist/domain/contracts/log.datasource.d.ts +0 -8
  129. package/dist/domain/contracts/pii.d.ts +0 -5
  130. package/dist/domain/services/index.d.ts +0 -1
  131. package/dist/domain/services/pii-redactor.d.ts +0 -10
  132. package/dist/domain/types/index.d.ts +0 -1
  133. package/dist/domain/types/log.types.d.ts +0 -28
  134. package/dist/domain/value-objects/index.d.ts +0 -1
  135. package/dist/domain/value-objects/log-level.js +0 -37
  136. package/dist/index.d.ts +0 -5
  137. package/dist/index.js +0 -10
  138. package/dist/infrastructure/adapters/composite.datasource.d.ts +0 -11
  139. package/dist/infrastructure/adapters/composite.datasource.js +0 -46
  140. package/dist/infrastructure/adapters/index.d.ts +0 -1
  141. package/dist/presentation/factory/index.d.ts +0 -1
  142. /package/dist/{domain/contracts/log.datasource.js → src/domain/ports/create-logger-options.port.js} +0 -0
  143. /package/dist/{domain/contracts/logger.js → src/domain/ports/log-datasource.port.js} +0 -0
  144. /package/dist/{domain/contracts/pii.js → src/domain/ports/logger-factory-config.port.js} +0 -0
  145. /package/dist/{domain/types/log.types.js → src/domain/ports/logger-service.port.js} +0 -0
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const services_1 = require("../../../src/domain/services");
4
+ describe("toPiiRegex()", () => {
5
+ // ---------------------------------------------------------------------------
6
+ // 1️⃣ Patrón válido con flags por defecto (g)
7
+ // ---------------------------------------------------------------------------
8
+ it("debe crear un RegExp válido con flags 'g' por defecto", () => {
9
+ const props = {
10
+ pattern: "\\d+",
11
+ replaceWith: "[NUM]",
12
+ };
13
+ const regex = (0, services_1.toPiiRegex)(props);
14
+ expect(regex).toBeInstanceOf(RegExp);
15
+ expect(regex.source).toBe("\\d+");
16
+ expect(regex.flags).toBe("g");
17
+ const result = "abc123def456".replace(regex, props.replaceWith);
18
+ expect(result).toBe("abc[NUM]def[NUM]");
19
+ });
20
+ // ---------------------------------------------------------------------------
21
+ // 2️⃣ Patrón válido con flags personalizados
22
+ // ---------------------------------------------------------------------------
23
+ it("debe respetar los flags personalizados si son válidos", () => {
24
+ const props = {
25
+ pattern: "test",
26
+ flags: "gi",
27
+ replaceWith: "X",
28
+ };
29
+ const regex = (0, services_1.toPiiRegex)(props);
30
+ expect(regex.source).toBe("test");
31
+ expect(regex.flags).toBe("gi");
32
+ expect("TeSt 1, test 2".replace(regex, props.replaceWith)).toBe("X 1, X 2");
33
+ });
34
+ // ---------------------------------------------------------------------------
35
+ // 3️⃣ Patrón inválido → debe retornar el RegExp fallback /$a/
36
+ // ---------------------------------------------------------------------------
37
+ it("debe retornar un RegExp imposible (/\\$a/) si el patrón es inválido", () => {
38
+ const props = {
39
+ pattern: "[unclosed",
40
+ flags: "g",
41
+ replaceWith: "X",
42
+ };
43
+ const regex = (0, services_1.toPiiRegex)(props);
44
+ // El fallback esperado es /$a/
45
+ expect(regex).toBeInstanceOf(RegExp);
46
+ expect(regex.source).toBe("$a");
47
+ expect(regex.test("cualquier texto")).toBe(false);
48
+ });
49
+ // ---------------------------------------------------------------------------
50
+ // 4️⃣ Flags inválidos → también debe usar el fallback
51
+ // ---------------------------------------------------------------------------
52
+ it("debe usar el fallback si los flags son inválidos", () => {
53
+ const props = {
54
+ pattern: "\\d+",
55
+ flags: "z", // flag inválido
56
+ replaceWith: "X",
57
+ };
58
+ const regex = (0, services_1.toPiiRegex)(props);
59
+ expect(regex.source).toBe("$a");
60
+ expect(regex.test("123")).toBe(false);
61
+ });
62
+ // ---------------------------------------------------------------------------
63
+ // 5️⃣ Asegura que el fallback nunca hace match con ejemplos comunes
64
+ // ---------------------------------------------------------------------------
65
+ it("el fallback nunca debe hacer match con strings comunes", () => {
66
+ const props = {
67
+ pattern: "\\", // clarísimamente inválido
68
+ replaceWith: "X",
69
+ };
70
+ const regex = (0, services_1.toPiiRegex)(props);
71
+ const samples = [
72
+ "",
73
+ "abc",
74
+ "123",
75
+ "user@test.com",
76
+ "tarjeta 4111-1111-1111-1111",
77
+ ];
78
+ for (const s of samples) {
79
+ expect(regex.test(s)).toBe(false);
80
+ }
81
+ });
82
+ });
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const infrastructure_1 = require("src/infrastructure");
4
+ const src_1 = require("../../../src");
5
+ describe("DataSourceService", () => {
6
+ const log = {
7
+ level: src_1.LogLevel.INFO,
8
+ message: "test log",
9
+ timestamp: Date.now(),
10
+ meta: {
11
+ userId: "12345",
12
+ },
13
+ };
14
+ const makeDsMock = () => ({
15
+ name: "mock",
16
+ save: jest.fn(),
17
+ find: jest.fn(),
18
+ flush: jest.fn(),
19
+ dispose: jest.fn(),
20
+ });
21
+ beforeEach(() => {
22
+ jest.clearAllMocks();
23
+ });
24
+ // -------------------------------------------------------------------------
25
+ // SAVE
26
+ // -------------------------------------------------------------------------
27
+ test("save() debe ejecutar save en todos los datasources", async () => {
28
+ const ds1 = makeDsMock();
29
+ const ds2 = makeDsMock();
30
+ const service = new infrastructure_1.DataSourceService([ds1, ds2]);
31
+ await service.save(log);
32
+ expect(ds1.save).toHaveBeenCalledWith(log);
33
+ expect(ds2.save).toHaveBeenCalledWith(log);
34
+ expect(ds1.save).toHaveBeenCalledTimes(1);
35
+ expect(ds2.save).toHaveBeenCalledTimes(1);
36
+ });
37
+ test("save() debe continuar incluso si uno de los datasources falla y llamar al error handler", async () => {
38
+ const ds1 = makeDsMock();
39
+ const ds2 = makeDsMock();
40
+ ds1.save.mockResolvedValue(undefined);
41
+ ds2.save.mockRejectedValue(new Error("failure"));
42
+ const onError = jest.fn();
43
+ const service = new infrastructure_1.DataSourceService([ds1, ds2], onError);
44
+ await service.save(log);
45
+ expect(ds1.save).toHaveBeenCalled();
46
+ expect(ds2.save).toHaveBeenCalled();
47
+ expect(onError).toHaveBeenCalledTimes(1);
48
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({
49
+ operation: "save",
50
+ datasourceName: "mock",
51
+ }));
52
+ // Opcional: validar que la razón sea el Error original
53
+ expect(onError.mock.calls[0][0].reason).toBeInstanceOf(Error);
54
+ expect(onError.mock.calls[0][0].reason.message).toBe("failure");
55
+ });
56
+ // -------------------------------------------------------------------------
57
+ // FIND
58
+ // -------------------------------------------------------------------------
59
+ test("find() debe concatenar resultados de varios datasources y ordenarlos desc por timestamp", async () => {
60
+ const ds1 = makeDsMock();
61
+ const ds2 = makeDsMock();
62
+ const logs1 = [
63
+ { level: src_1.LogLevel.INFO, message: "a", timestamp: 100 },
64
+ { level: src_1.LogLevel.WARN, message: "b", timestamp: 300 },
65
+ ];
66
+ const logs2 = [
67
+ { level: src_1.LogLevel.ERROR, message: "c", timestamp: 200 },
68
+ ];
69
+ ds1.find.mockResolvedValue(logs1);
70
+ ds2.find.mockResolvedValue(logs2);
71
+ const service = new infrastructure_1.DataSourceService([ds1, ds2]);
72
+ const result = await service.find();
73
+ expect(result).toHaveLength(3);
74
+ expect(result.map((l) => l.timestamp)).toEqual([300, 200, 100]);
75
+ });
76
+ test("find() ignora datasources que retornen error en find() y llama al error handler", async () => {
77
+ const ds1 = makeDsMock();
78
+ const ds2 = makeDsMock();
79
+ ds1.find.mockRejectedValue(new Error("ds1 fail"));
80
+ ds2.find.mockResolvedValue([
81
+ { id: "1", level: src_1.LogLevel.INFO, message: "ok", timestamp: 123 },
82
+ ]);
83
+ const onError = jest.fn();
84
+ const service = new infrastructure_1.DataSourceService([ds1, ds2], onError);
85
+ const result = await service.find();
86
+ // Sigue devolviendo solo los logs válidos
87
+ expect(result).toHaveLength(1);
88
+ expect(result[0].level).toBe(src_1.LogLevel.INFO);
89
+ // Y registra el error del datasource que falló
90
+ expect(onError).toHaveBeenCalledTimes(1);
91
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({
92
+ operation: "find",
93
+ datasourceName: "mock",
94
+ }));
95
+ expect(onError.mock.calls[0][0].reason).toBeInstanceOf(Error);
96
+ expect(onError.mock.calls[0][0].reason.message).toBe("ds1 fail");
97
+ });
98
+ // -------------------------------------------------------------------------
99
+ // FLUSH
100
+ // -------------------------------------------------------------------------
101
+ test("flush() debe llamar flush en todos los datasources que implementen flush()", async () => {
102
+ const ds1 = makeDsMock();
103
+ const ds2 = makeDsMock();
104
+ const service = new infrastructure_1.DataSourceService([ds1, ds2]);
105
+ await service.flush();
106
+ expect(ds1.flush).toHaveBeenCalledTimes(1);
107
+ expect(ds2.flush).toHaveBeenCalledTimes(1);
108
+ });
109
+ // -------------------------------------------------------------------------
110
+ // DISPOSE
111
+ // -------------------------------------------------------------------------
112
+ test("dispose() debe llamar dispose en todos los datasources", async () => {
113
+ const ds1 = makeDsMock();
114
+ const ds2 = makeDsMock();
115
+ const service = new infrastructure_1.DataSourceService([ds1, ds2]);
116
+ await service.dispose();
117
+ expect(ds1.dispose).toHaveBeenCalledTimes(1);
118
+ expect(ds2.dispose).toHaveBeenCalledTimes(1);
119
+ });
120
+ // -------------------------------------------------------------------------
121
+ // CONSTRUCTOR DEFENSIVO
122
+ // -------------------------------------------------------------------------
123
+ test("constructor debe filtrar targets inválidos (null/undefined)", async () => {
124
+ const ds1 = makeDsMock();
125
+ const service = new infrastructure_1.DataSourceService([ds1, null, undefined]);
126
+ expect(service.targets).toHaveLength(1);
127
+ });
128
+ });
@@ -0,0 +1,5 @@
1
+ import { IPiiRedactor } from "../../src/domain/ports";
2
+ export type PiiRedactorMock = IPiiRedactor & {
3
+ redact: jest.Mock;
4
+ };
5
+ export declare function createPiiRedactorMock(): PiiRedactorMock;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPiiRedactorMock = createPiiRedactorMock;
4
+ function createPiiRedactorMock() {
5
+ const redact = jest.fn((value) => value);
6
+ return {
7
+ redact,
8
+ updateOptions: jest.fn(),
9
+ };
10
+ }
package/package.json CHANGED
@@ -1,32 +1,40 @@
1
1
  {
2
2
  "name": "@jmlq/logger",
3
- "version": "0.1.0-alpha.7",
4
- "author": "MLahuasi",
5
- "license": "MIT",
3
+ "description": "logger package with clean architecture",
4
+ "version": "0.1.0-alpha.8",
6
5
  "main": "dist/index.js",
7
6
  "types": "dist/index.d.ts",
8
- "files": [
9
- "dist"
10
- ],
11
7
  "scripts": {
12
8
  "build": "tsc -p tsconfig.json",
13
9
  "prepublishOnly": "npm run build",
14
10
  "test": "jest --passWithNoTests",
15
11
  "test:watch": "jest --watch",
16
- "test:cov": "jest --coverage"
12
+ "test:coverage": "jest --coverage",
13
+ "example:help": "tsx examples/index.example.ts help",
14
+ "example:all": "tsx examples/index.example.ts",
15
+ "example:domain-services": "tsx examples/index.example.ts domain-services",
16
+ "example:services": "tsx examples/index.example.ts services",
17
+ "example:use-cases": "tsx examples/index.example.ts use-cases",
18
+ "example:factories": "tsx examples/index.example.ts factories"
17
19
  },
20
+ "keywords": [
21
+ "logger",
22
+ "clean-architecture",
23
+ "typescript"
24
+ ],
25
+ "author": "MLahuasi",
26
+ "license": "MIT",
18
27
  "devDependencies": {
19
- "@swc/core": "^1.13.5",
20
- "@swc/jest": "^0.2.39",
21
- "@types/jest": "^30.0.0",
22
- "@types/node": "^24.3.0",
23
- "jest": "^30.1.3",
24
- "tsx": "^4.20.5",
25
- "typescript": "^5.9.2"
28
+ "@swc/core": "^1.3.95",
29
+ "@swc/jest": "^0.2.29",
30
+ "@types/bcryptjs": "^2.4.5",
31
+ "@types/jest": "^29.5.8",
32
+ "@types/node": "^20.8.10",
33
+ "jest": "^29.7.0",
34
+ "tsx": "^4.1.4",
35
+ "typescript": "^5.2.2"
26
36
  },
27
- "overrides": {
28
- "test-exclude": "^7.0.1",
29
- "glob": "^10.4.5",
30
- "minimatch": "^9.0.5"
31
- }
37
+ "files": [
38
+ "dist"
39
+ ]
32
40
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2024-2025 mlahuasi
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the “Software”), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in
13
- all copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
- THE SOFTWARE.
@@ -1,6 +0,0 @@
1
- import { ILogDatasource } from "../../domain/contracts";
2
- export declare class FlushBuffers {
3
- private readonly ds;
4
- constructor(ds: ILogDatasource);
5
- execute(): Promise<void>;
6
- }
@@ -1,7 +0,0 @@
1
- import { ILogDatasource } from "../../domain/contracts";
2
- import { IGetLogsFilter, ILog } from "../../domain/types";
3
- export declare class GetLogs {
4
- private readonly ds;
5
- constructor(ds: ILogDatasource);
6
- execute(filter?: IGetLogsFilter): Promise<ILog[]>;
7
- }
@@ -1,3 +0,0 @@
1
- export * from "./save-log";
2
- export * from "./get-logs";
3
- export * from "./flush-buffers";
@@ -1,13 +0,0 @@
1
- import { ILogDatasource, IPiiRedactor } from "../../domain/contracts";
2
- import { LogMessage } from "../../domain/types";
3
- import { LogLevel } from "../../domain/value-objects";
4
- export interface SaveLogDeps {
5
- ds: ILogDatasource;
6
- minLevel: LogLevel;
7
- redactor: IPiiRedactor;
8
- }
9
- export declare class SaveLog {
10
- private readonly deps;
11
- constructor(deps: SaveLogDeps);
12
- execute(level: LogLevel, message: LogMessage, meta?: unknown): Promise<void>;
13
- }
@@ -1,30 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SaveLog = void 0;
4
- // Normaliza el mensaje: si es función, la evalúa; si es objeto, se redacta; si es string, se redacta
5
- function normalizeMessage(message, redactor) {
6
- const resolved = typeof message === "function" ? message() : message; // eval laziness
7
- return redactor.redact(resolved);
8
- }
9
- class SaveLog {
10
- constructor(deps) {
11
- this.deps = deps;
12
- }
13
- async execute(level, message, meta) {
14
- // 1) Filtro por nivel (evita hacer trabajo innecesario)
15
- if (level < this.deps.minLevel)
16
- return; // no se loggea
17
- // 2) Normalización + PII
18
- const normalized = normalizeMessage(message, this.deps.redactor);
19
- // 3) Construcción del evento
20
- const log = {
21
- level,
22
- message: normalized,
23
- meta: meta === undefined ? undefined : this.deps.redactor.redact(meta),
24
- timestamp: Date.now(),
25
- };
26
- // 4) Persistencia (fan-out lo maneja el ds si es composite)
27
- await this.deps.ds.save(log);
28
- }
29
- }
30
- exports.SaveLog = SaveLog;
@@ -1,3 +0,0 @@
1
- export * from "./log.datasource";
2
- export * from "./logger";
3
- export * from "./pii";
@@ -1,8 +0,0 @@
1
- import { IGetLogsFilter, ILog } from "../types";
2
- export interface ILogDatasource {
3
- save(log: ILog): Promise<void>;
4
- find?(filter?: IGetLogsFilter): Promise<ILog[]>;
5
- flush?(): Promise<void>;
6
- dispose?(): Promise<void>;
7
- readonly name?: string;
8
- }
@@ -1,5 +0,0 @@
1
- import { PiiOptions } from "../types";
2
- export interface IPiiRedactor {
3
- redact<T = unknown>(value: T): T;
4
- updateOptions?(opts: PiiOptions): void;
5
- }
@@ -1 +0,0 @@
1
- export * from "./pii-redactor";
@@ -1,10 +0,0 @@
1
- import { IPiiRedactor } from "../contracts";
2
- import { PiiOptions } from "../types";
3
- export declare class PiiRedactor implements IPiiRedactor {
4
- private options;
5
- constructor(options?: PiiOptions);
6
- updateOptions(opts: PiiOptions): void;
7
- redact<T = unknown>(value: T): T;
8
- private applyPatterns;
9
- private redactDeep;
10
- }
@@ -1 +0,0 @@
1
- export * from "./log.types";
@@ -1,28 +0,0 @@
1
- import { LogLevel } from "../value-objects";
2
- export type LogMessage = string | Record<string, unknown> | (() => string | Record<string, unknown>);
3
- export interface ILog {
4
- level: LogLevel;
5
- message: string | Record<string, unknown>;
6
- meta?: unknown;
7
- timestamp: number;
8
- }
9
- export interface IGetLogsFilter {
10
- levelMin?: LogLevel;
11
- since?: number;
12
- until?: number;
13
- limit?: number;
14
- offset?: number;
15
- query?: string;
16
- }
17
- export interface PiiReplacement {
18
- pattern: string;
19
- flags?: string;
20
- replaceWith: string;
21
- }
22
- export interface PiiOptions {
23
- enabled?: boolean;
24
- whitelistKeys?: string[];
25
- blacklistKeys?: string[];
26
- patterns?: PiiReplacement[];
27
- deep?: boolean;
28
- }
@@ -1 +0,0 @@
1
- export * from "./log-level";
@@ -1,37 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LogLevel = void 0;
4
- exports.toLogLevel = toLogLevel;
5
- var LogLevel;
6
- (function (LogLevel) {
7
- // Orden creciente permite comparar por severidad (trace < debug < ...)
8
- LogLevel[LogLevel["TRACE"] = 10] = "TRACE";
9
- LogLevel[LogLevel["DEBUG"] = 20] = "DEBUG";
10
- LogLevel[LogLevel["INFO"] = 30] = "INFO";
11
- LogLevel[LogLevel["WARN"] = 40] = "WARN";
12
- LogLevel[LogLevel["ERROR"] = 50] = "ERROR";
13
- LogLevel[LogLevel["FATAL"] = 60] = "FATAL";
14
- })(LogLevel || (exports.LogLevel = LogLevel = {}));
15
- // Convierte string a LogLevel con fallback seguro
16
- function toLogLevel(level, def = LogLevel.INFO) {
17
- if (typeof level === "number")
18
- return (Object.values(LogLevel).includes(level) ? level : def);
19
- if (!level)
20
- return def;
21
- switch (String(level).toLowerCase()) {
22
- case "trace":
23
- return LogLevel.TRACE;
24
- case "debug":
25
- return LogLevel.DEBUG;
26
- case "info":
27
- return LogLevel.INFO;
28
- case "warn":
29
- return LogLevel.WARN;
30
- case "error":
31
- return LogLevel.ERROR;
32
- case "fatal":
33
- return LogLevel.FATAL;
34
- default:
35
- return def; // evita lanzar excepción por valores inesperados
36
- }
37
- }
package/dist/index.d.ts DELETED
@@ -1,5 +0,0 @@
1
- export { LogLevel, toLogLevel } from "./domain/value-objects";
2
- export type { LogMessage, ILog, IGetLogsFilter, PiiOptions, PiiReplacement, } from "./domain/types";
3
- export type { LogDatasourcePort, ILogger, ICreateLoggerOptions, ILogDatasource, } from "./domain/contracts";
4
- export { createLogger } from "./presentation/factory";
5
- export { CompositeDatasource } from "./infrastructure/adapters";
package/dist/index.js DELETED
@@ -1,10 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CompositeDatasource = exports.createLogger = exports.toLogLevel = exports.LogLevel = void 0;
4
- var value_objects_1 = require("./domain/value-objects");
5
- Object.defineProperty(exports, "LogLevel", { enumerable: true, get: function () { return value_objects_1.LogLevel; } });
6
- Object.defineProperty(exports, "toLogLevel", { enumerable: true, get: function () { return value_objects_1.toLogLevel; } });
7
- var factory_1 = require("./presentation/factory");
8
- Object.defineProperty(exports, "createLogger", { enumerable: true, get: function () { return factory_1.createLogger; } });
9
- var adapters_1 = require("./infrastructure/adapters");
10
- Object.defineProperty(exports, "CompositeDatasource", { enumerable: true, get: function () { return adapters_1.CompositeDatasource; } });
@@ -1,11 +0,0 @@
1
- import { ILogDatasource } from "../../domain/contracts";
2
- import { IGetLogsFilter, ILog } from "../../domain/types";
3
- export declare class CompositeDatasource implements ILogDatasource {
4
- private readonly targets;
5
- readonly name = "composite";
6
- constructor(targets: ILogDatasource[]);
7
- save(log: ILog): Promise<void>;
8
- find(filter?: IGetLogsFilter): Promise<ILog[]>;
9
- flush(): Promise<void>;
10
- dispose(): Promise<void>;
11
- }
@@ -1,46 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CompositeDatasource = void 0;
4
- // CompositeDatasource: fan-out hacia múltiples datasources
5
- class CompositeDatasource {
6
- constructor(targets) {
7
- this.targets = targets;
8
- this.name = "composite";
9
- // Filtro targets válidos (defensivo). Evita null/undefined
10
- this.targets = (targets ?? []).filter(Boolean);
11
- }
12
- async save(log) {
13
- // Ejecuta todos en paralelo y NO falla el todo si uno falla
14
- const results = await Promise.allSettled(this.targets.map((ds) => ds.save(log)));
15
- // Log de errores silencioso (el logger real no debe auto-dependerse)
16
- for (let i = 0; i < results.length; i++) {
17
- const r = results[i];
18
- if (r.status === "rejected") {
19
- // Preferible: exponer un hook externo; aquí solo console.warn por simplicidad
20
- // eslint-disable-next-line no-console
21
- console.warn(`[CompositeDatasource] save error in ds#${i} (${this.targets[i]?.name ?? "unknown"})`, r.reason);
22
- }
23
- }
24
- }
25
- async find(filter) {
26
- // Si varios ds soportan find, se concatena y ordena por timestamp desc
27
- const results = await Promise.allSettled(this.targets.map((ds) => ds.find?.(filter)));
28
- const logs = [];
29
- for (const r of results) {
30
- if (r.status === "fulfilled" && Array.isArray(r.value))
31
- logs.push(...r.value);
32
- }
33
- // Orden descendente por timestamp (más recientes primero)
34
- logs.sort((a, b) => b.timestamp - a.timestamp);
35
- return logs;
36
- }
37
- async flush() {
38
- // Ejecuta flush donde esté disponible
39
- await Promise.allSettled(this.targets.map((ds) => ds.flush?.()));
40
- }
41
- async dispose() {
42
- // Libera recursos en todos los ds
43
- await Promise.allSettled(this.targets.map((ds) => ds.dispose?.()));
44
- }
45
- }
46
- exports.CompositeDatasource = CompositeDatasource;
@@ -1 +0,0 @@
1
- export * from "./composite.datasource";
@@ -1 +0,0 @@
1
- export * from "./create-logger";