logixia 2.0.0 → 2.0.4
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/README.md +46 -29
- package/dist/async-context-B05ArHgM.mjs +134 -0
- package/dist/async-context-B05ArHgM.mjs.map +1 -0
- package/dist/async-context-DTQgi8f7.js +150 -0
- package/dist/async-context-DTQgi8f7.js.map +1 -0
- package/dist/{azure-monitor.transport-CHnjVRF-.mjs → azure-monitor.transport-BPbgjATu.mjs} +27 -15
- package/dist/azure-monitor.transport-BPbgjATu.mjs.map +1 -0
- package/dist/{azure-monitor.transport-Cn_3Usvu.d.ts → azure-monitor.transport-C7kYyZUW.d.mts} +3 -6
- package/dist/azure-monitor.transport-C7kYyZUW.d.mts.map +1 -0
- package/dist/{azure-monitor.transport-CrvfHd9C.js → azure-monitor.transport-CwbOLZHB.js} +32 -20
- package/dist/azure-monitor.transport-CwbOLZHB.js.map +1 -0
- package/dist/{azure-monitor.transport-D7Da4RAb.d.mts → azure-monitor.transport-DV03Z5P4.d.ts} +3 -6
- package/dist/azure-monitor.transport-DV03Z5P4.d.ts.map +1 -0
- package/dist/azure.d.mts +1 -2
- package/dist/azure.d.ts +1 -2
- package/dist/azure.js +3 -6
- package/dist/azure.mjs +1 -6
- package/dist/{batch-buffer-PGvSgbmd.mjs → batch-buffer-0fgLmIPn.mjs} +21 -7
- package/dist/batch-buffer-0fgLmIPn.mjs.map +1 -0
- package/dist/{batch-buffer-BY-mRWIK.js → batch-buffer-DT4gdXmf.js} +53 -40
- package/dist/batch-buffer-DT4gdXmf.js.map +1 -0
- package/dist/browser.d.mts +45 -25
- package/dist/browser.d.mts.map +1 -1
- package/dist/browser.d.ts +45 -25
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +420 -53
- package/dist/browser.js.map +1 -1
- package/dist/browser.mjs +421 -56
- package/dist/browser.mjs.map +1 -1
- package/dist/{builder-0gEzRopq.mjs → builder-D70z6kjj.mjs} +212 -104
- package/dist/builder-D70z6kjj.mjs.map +1 -0
- package/dist/{builder-D44QktIo.js → builder-M7NoaugM.js} +355 -249
- package/dist/builder-M7NoaugM.js.map +1 -0
- package/dist/cli/index.js +59 -59
- package/dist/cloudwatch.d.mts +1 -2
- package/dist/cloudwatch.d.ts +1 -2
- package/dist/cloudwatch.js +3 -7
- package/dist/cloudwatch.mjs +1 -7
- package/dist/{cloudwatch.transport-BO1ahxw-.js → cloudwatch.transport-B2wKQFF7.js} +61 -36
- package/dist/cloudwatch.transport-B2wKQFF7.js.map +1 -0
- package/dist/{cloudwatch.transport-DZ6ies7g.mjs → cloudwatch.transport-BTvYfLs9.mjs} +54 -28
- package/dist/cloudwatch.transport-BTvYfLs9.mjs.map +1 -0
- package/dist/{cloudwatch.transport-DsEq633o.d.ts → cloudwatch.transport-Bf7L4I59.d.ts} +2 -6
- package/dist/cloudwatch.transport-Bf7L4I59.d.ts.map +1 -0
- package/dist/{cloudwatch.transport-UlyZFWMn.d.mts → cloudwatch.transport-Rj4yTpRn.d.mts} +2 -6
- package/dist/cloudwatch.transport-Rj4yTpRn.d.mts.map +1 -0
- package/dist/{coerce.utils-Cu6IUTgX.mjs → coerce.utils-B_rEudCn.mjs} +3 -4
- package/dist/{coerce.utils-Cu6IUTgX.mjs.map → coerce.utils-B_rEudCn.mjs.map} +1 -1
- package/dist/{coerce.utils-B-LilukN.js → coerce.utils-C1C5sIX0.js} +8 -10
- package/dist/{coerce.utils-B-LilukN.js.map → coerce.utils-C1C5sIX0.js.map} +1 -1
- package/dist/correlation.d.mts +13 -16
- package/dist/correlation.d.mts.map +1 -1
- package/dist/correlation.d.ts +13 -16
- package/dist/correlation.d.ts.map +1 -1
- package/dist/correlation.js +58 -9
- package/dist/correlation.js.map +1 -1
- package/dist/correlation.mjs +56 -6
- package/dist/correlation.mjs.map +1 -1
- package/dist/{entry-fields-BJkuPnIg.mjs → entry-fields-CGuvT2R0.mjs} +5 -6
- package/dist/entry-fields-CGuvT2R0.mjs.map +1 -0
- package/dist/{entry-fields-BvOLFlJ4.js → entry-fields-RLd1jCoR.js} +10 -12
- package/dist/entry-fields-RLd1jCoR.js.map +1 -0
- package/dist/gcp.d.mts +1 -2
- package/dist/gcp.d.ts +1 -2
- package/dist/gcp.js +3 -7
- package/dist/gcp.mjs +1 -7
- package/dist/{gcp.transport-B7oc97sG.d.ts → gcp.transport-C5D72b1g.d.mts} +3 -6
- package/dist/gcp.transport-C5D72b1g.d.mts.map +1 -0
- package/dist/{gcp.transport-GrJurKo8.d.mts → gcp.transport-CFQfdAOK.d.ts} +3 -6
- package/dist/gcp.transport-CFQfdAOK.d.ts.map +1 -0
- package/dist/{gcp.transport-DBX5TPIy.mjs → gcp.transport-CGKopAhQ.mjs} +55 -16
- package/dist/gcp.transport-CGKopAhQ.mjs.map +1 -0
- package/dist/{gcp.transport-CHV8MGgz.js → gcp.transport-KZe9hCAR.js} +60 -22
- package/dist/gcp.transport-KZe9hCAR.js.map +1 -0
- package/dist/{index-DhIoploR.d.ts → index-DwozbmB4.d.ts} +3 -8
- package/dist/index-DwozbmB4.d.ts.map +1 -0
- package/dist/{index-3mw5gaCw.d.mts → index-xqaJtAZn.d.mts} +3 -8
- package/dist/index-xqaJtAZn.d.mts.map +1 -0
- package/dist/index.d.mts +106 -165
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +105 -164
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +164 -261
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +147 -243
- package/dist/index.mjs.map +1 -1
- package/dist/internal-log-b0Vp4qrB.js +183 -0
- package/dist/internal-log-b0Vp4qrB.js.map +1 -0
- package/dist/internal-log-uCSd1PMc.mjs +142 -0
- package/dist/internal-log-uCSd1PMc.mjs.map +1 -0
- package/dist/{logitron-logger-UVeN-mQm.d.ts → logitron-logger-D2B75Oc7.d.ts} +116 -8
- package/dist/logitron-logger-D2B75Oc7.d.ts.map +1 -0
- package/dist/{logitron-logger-BFDSO8Io.d.mts → logitron-logger-oEd6wNhf.d.mts} +116 -8
- package/dist/logitron-logger-oEd6wNhf.d.mts.map +1 -0
- package/dist/middleware.d.mts +10 -12
- package/dist/middleware.d.mts.map +1 -1
- package/dist/middleware.d.ts +10 -12
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +16 -47
- package/dist/middleware.js.map +1 -1
- package/dist/middleware.mjs +13 -45
- package/dist/middleware.mjs.map +1 -1
- package/dist/nest.d.mts +26 -44
- package/dist/nest.d.mts.map +1 -1
- package/dist/nest.d.ts +26 -44
- package/dist/nest.d.ts.map +1 -1
- package/dist/nest.js +116 -132
- package/dist/nest.js.map +1 -1
- package/dist/nest.mjs +59 -73
- package/dist/nest.mjs.map +1 -1
- package/dist/{trace.utils-CvXgaiQT.mjs → request-trace-C_fvIDv4.mjs} +44 -9
- package/dist/request-trace-C_fvIDv4.mjs.map +1 -0
- package/dist/{trace.utils-DpBOLDtq.js → request-trace-wTJdKp6-.js} +121 -77
- package/dist/request-trace-wTJdKp6-.js.map +1 -0
- package/dist/rolldown-runtime-D3PmRqjj.mjs +4 -0
- package/dist/{safe-stringify-DJ66tW5I.mjs → safe-stringify-BMRl3EX3.mjs} +3 -4
- package/dist/safe-stringify-BMRl3EX3.mjs.map +1 -0
- package/dist/{safe-stringify-DWo3aZp_.js → safe-stringify-DLz1Kz3o.js} +23 -25
- package/dist/safe-stringify-DLz1Kz3o.js.map +1 -0
- package/dist/{search-CNh9uVwR.d.ts → search-BH33XhuU.d.mts} +2 -22
- package/dist/search-BH33XhuU.d.mts.map +1 -0
- package/dist/{search-BFbu_oVn.mjs → search-CWMVYC-R.mjs} +22 -39
- package/dist/search-CWMVYC-R.mjs.map +1 -0
- package/dist/{search-DXANsQ2n.d.mts → search-CazwyX5Z.d.ts} +2 -22
- package/dist/search-CazwyX5Z.d.ts.map +1 -0
- package/dist/{search-C4V0OMEn.js → search-DUfWuzFP.js} +52 -69
- package/dist/search-DUfWuzFP.js.map +1 -0
- package/dist/search.d.mts +2 -4
- package/dist/search.d.ts +2 -4
- package/dist/search.js +3 -4
- package/dist/search.mjs +1 -4
- package/dist/secret-config-BegMLkYl.mjs +209 -0
- package/dist/secret-config-BegMLkYl.mjs.map +1 -0
- package/dist/secret-config-CBZBs0p1.js +271 -0
- package/dist/secret-config-CBZBs0p1.js.map +1 -0
- package/dist/{slack.transport-Bzw7sucI.mjs → slack.transport-Ce96JBDk.mjs} +212 -31
- package/dist/slack.transport-Ce96JBDk.mjs.map +1 -0
- package/dist/{slack.transport-BfJRouB2.js → slack.transport-Dlx3xvb7.js} +234 -41
- package/dist/slack.transport-Dlx3xvb7.js.map +1 -0
- package/dist/{slack.transport-BZzoXDPn.d.mts → slack.transport-DrirgDNy.d.ts} +56 -9
- package/dist/slack.transport-DrirgDNy.d.ts.map +1 -0
- package/dist/{slack.transport-CXjQYOes.d.ts → slack.transport-DxHOXlLu.d.mts} +56 -9
- package/dist/slack.transport-DxHOXlLu.d.mts.map +1 -0
- package/dist/testing.d.mts +3 -8
- package/dist/testing.d.mts.map +1 -1
- package/dist/testing.d.ts +3 -8
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +3 -4
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +2 -3
- package/dist/testing.mjs.map +1 -1
- package/dist/{transport.manager-CXbKKdVE.js → transport.manager-DkcEOlqV.js} +164 -160
- package/dist/transport.manager-DkcEOlqV.js.map +1 -0
- package/dist/{transport.manager-BiuCAJd2.mjs → transport.manager-eZ_EeC00.mjs} +108 -99
- package/dist/transport.manager-eZ_EeC00.mjs.map +1 -0
- package/dist/{transport.types-CGoHpWQR.d.ts → transport.types-BJVL1QQl.d.mts} +1 -3
- package/dist/transport.types-BJVL1QQl.d.mts.map +1 -0
- package/dist/{transport.types-BMnurPcc.d.mts → transport.types-BJVL1QQl.d.ts} +1 -3
- package/dist/transport.types-BJVL1QQl.d.ts.map +1 -0
- package/dist/transports.d.mts +22 -36
- package/dist/transports.d.mts.map +1 -1
- package/dist/transports.d.ts +22 -36
- package/dist/transports.d.ts.map +1 -1
- package/dist/transports.js +10 -13
- package/dist/transports.mjs +7 -13
- package/dist/worker-entry.js +337 -87
- package/dist/worker.d.mts +1 -2
- package/dist/worker.d.ts +1 -2
- package/dist/worker.js +3 -4
- package/dist/worker.mjs +1 -4
- package/dist/{worker.transport-CdzSZJmw.d.ts → worker.transport-BuPwBi3d.d.ts} +2 -6
- package/dist/worker.transport-BuPwBi3d.d.ts.map +1 -0
- package/dist/{worker.transport-BdPxu3PN.js → worker.transport-C6GNl_r2.js} +44 -14
- package/dist/worker.transport-C6GNl_r2.js.map +1 -0
- package/dist/{worker.transport-lPxO2MVL.mjs → worker.transport-DLVA4y2e.mjs} +39 -9
- package/dist/worker.transport-DLVA4y2e.mjs.map +1 -0
- package/dist/{worker.transport-JvGPog3C.d.mts → worker.transport-hJay1wxA.d.mts} +2 -6
- package/dist/worker.transport-hJay1wxA.d.mts.map +1 -0
- package/package.json +19 -11
- package/dist/async-context-BzJrbfQs.mjs +0 -72
- package/dist/async-context-BzJrbfQs.mjs.map +0 -1
- package/dist/async-context-DyQQYq3I.js +0 -92
- package/dist/async-context-DyQQYq3I.js.map +0 -1
- package/dist/azure-monitor.transport-CHnjVRF-.mjs.map +0 -1
- package/dist/azure-monitor.transport-Cn_3Usvu.d.ts.map +0 -1
- package/dist/azure-monitor.transport-CrvfHd9C.js.map +0 -1
- package/dist/azure-monitor.transport-D7Da4RAb.d.mts.map +0 -1
- package/dist/batch-buffer-BY-mRWIK.js.map +0 -1
- package/dist/batch-buffer-PGvSgbmd.mjs.map +0 -1
- package/dist/builder-0gEzRopq.mjs.map +0 -1
- package/dist/builder-D44QktIo.js.map +0 -1
- package/dist/chunk-DLSkYcPk.mjs +0 -7
- package/dist/chunk-nOFOJqeH.js +0 -30
- package/dist/cloudwatch.transport-BO1ahxw-.js.map +0 -1
- package/dist/cloudwatch.transport-DZ6ies7g.mjs.map +0 -1
- package/dist/cloudwatch.transport-DsEq633o.d.ts.map +0 -1
- package/dist/cloudwatch.transport-UlyZFWMn.d.mts.map +0 -1
- package/dist/entry-fields-BJkuPnIg.mjs.map +0 -1
- package/dist/entry-fields-BvOLFlJ4.js.map +0 -1
- package/dist/gcp.transport-B7oc97sG.d.ts.map +0 -1
- package/dist/gcp.transport-CHV8MGgz.js.map +0 -1
- package/dist/gcp.transport-DBX5TPIy.mjs.map +0 -1
- package/dist/gcp.transport-GrJurKo8.d.mts.map +0 -1
- package/dist/index-3mw5gaCw.d.mts.map +0 -1
- package/dist/index-DhIoploR.d.ts.map +0 -1
- package/dist/internal-log-BUJYMZbE.js +0 -70
- package/dist/internal-log-BUJYMZbE.js.map +0 -1
- package/dist/internal-log-Cm8SOWSV.mjs +0 -52
- package/dist/internal-log-Cm8SOWSV.mjs.map +0 -1
- package/dist/logitron-logger-BFDSO8Io.d.mts.map +0 -1
- package/dist/logitron-logger-UVeN-mQm.d.ts.map +0 -1
- package/dist/safe-stringify-DJ66tW5I.mjs.map +0 -1
- package/dist/safe-stringify-DWo3aZp_.js.map +0 -1
- package/dist/search-BFbu_oVn.mjs.map +0 -1
- package/dist/search-C4V0OMEn.js.map +0 -1
- package/dist/search-CNh9uVwR.d.ts.map +0 -1
- package/dist/search-DXANsQ2n.d.mts.map +0 -1
- package/dist/slack.transport-BZzoXDPn.d.mts.map +0 -1
- package/dist/slack.transport-BfJRouB2.js.map +0 -1
- package/dist/slack.transport-Bzw7sucI.mjs.map +0 -1
- package/dist/slack.transport-CXjQYOes.d.ts.map +0 -1
- package/dist/trace.utils-CvXgaiQT.mjs.map +0 -1
- package/dist/trace.utils-DpBOLDtq.js.map +0 -1
- package/dist/transport.manager-BiuCAJd2.mjs.map +0 -1
- package/dist/transport.manager-CXbKKdVE.js.map +0 -1
- package/dist/transport.types-BMnurPcc.d.mts.map +0 -1
- package/dist/transport.types-CGoHpWQR.d.ts.map +0 -1
- package/dist/worker.transport-BdPxu3PN.js.map +0 -1
- package/dist/worker.transport-CdzSZJmw.d.ts.map +0 -1
- package/dist/worker.transport-JvGPog3C.d.mts.map +0 -1
- package/dist/worker.transport-lPxO2MVL.mjs.map +0 -1
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
import { l as ITransport, p as TransportLogEntry } from "./transport.types-
|
|
2
|
-
|
|
3
|
-
//#region src/transports/worker.transport.d.ts
|
|
4
|
-
|
|
1
|
+
import { l as ITransport, p as TransportLogEntry } from "./transport.types-BJVL1QQl.js";
|
|
5
2
|
interface WorkerTransportConfig {
|
|
6
3
|
/**
|
|
7
4
|
* Which built-in logixia transport to run inside the worker thread.
|
|
@@ -71,6 +68,5 @@ declare class WorkerTransport implements ITransport {
|
|
|
71
68
|
shutdown(): Promise<void>;
|
|
72
69
|
private drainBufferTo;
|
|
73
70
|
}
|
|
74
|
-
//#endregion
|
|
75
71
|
export { WorkerTransportConfig as n, WorkerTransport as t };
|
|
76
|
-
//# sourceMappingURL=worker.transport-
|
|
72
|
+
//# sourceMappingURL=worker.transport-BuPwBi3d.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker.transport-BuPwBi3d.d.ts","names":[],"sources":["../src/transports/worker.transport.ts"],"mappings":";UAwCiB;;;;;EAKf;;EAEA,iBAAiB;;;;;;EAMjB;;;;;EAKA;;;;;EAKA;;;;;;cAOW,2BAA2B;WACtB;WACA;WACA;WACA;UAER;UACA;mBACS;mBACA;UACT;mBACS;mBACA;;UAET;;UAEA;;mBAES;;mBAEA;EAEL,YAAA,QAAQ;UASZ;;YAqCE;UAIF;UAuBA;EASR,MAAM,OAAO;EAYP,SAAS;;;;;;;;EAiCT,SAAS;;EAkCT,YAAY;UAIV"}
|
|
@@ -1,11 +1,41 @@
|
|
|
1
|
-
const
|
|
2
|
-
const require_internal_log = require(
|
|
1
|
+
const require_secret_config = require("./secret-config-CBZBs0p1.js");
|
|
2
|
+
const require_internal_log = require("./internal-log-b0Vp4qrB.js");
|
|
3
3
|
let node_path = require("node:path");
|
|
4
|
-
node_path =
|
|
4
|
+
node_path = require_secret_config.__toESM(node_path);
|
|
5
5
|
let node_worker_threads = require("node:worker_threads");
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
// src/transports/worker.transport.ts
|
|
7
|
+
/**
|
|
8
|
+
* logixia — Worker Thread Transport
|
|
9
|
+
*
|
|
10
|
+
* Offloads JSON serialization and all I/O to a Node.js worker thread,
|
|
11
|
+
* completely eliminating any event-loop impact from logging. The main thread
|
|
12
|
+
* only posts a raw message to the worker — it never calls JSON.stringify or
|
|
13
|
+
* any I/O syscalls on the hot path.
|
|
14
|
+
*
|
|
15
|
+
* Architecture:
|
|
16
|
+
* Main thread → MessageChannel → Worker thread → Wrapped transport
|
|
17
|
+
*
|
|
18
|
+
* The worker runs an ordinary logixia transport (file, database, console…)
|
|
19
|
+
* inside its own event loop. If the worker crashes it is restarted automatically
|
|
20
|
+
* (up to `maxRestarts` times) and buffered messages are replayed.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```ts
|
|
24
|
+
* import { WorkerTransport } from 'logixia/worker';
|
|
25
|
+
*
|
|
26
|
+
* const logger = createLogger({
|
|
27
|
+
* transports: {
|
|
28
|
+
* // Run file transport inside a worker thread — zero event-loop impact
|
|
29
|
+
* worker: new WorkerTransport({
|
|
30
|
+
* transportType: 'file',
|
|
31
|
+
* transportConfig: { filename: 'app.log', dirname: './logs' },
|
|
32
|
+
* bufferSize: 500,
|
|
33
|
+
* maxRestarts: 3,
|
|
34
|
+
* }),
|
|
35
|
+
* },
|
|
36
|
+
* });
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
9
39
|
/**
|
|
10
40
|
* Transport that runs a wrapped transport inside a dedicated Node.js worker
|
|
11
41
|
* thread, completely removing JSON serialization and I/O from the main event loop.
|
|
@@ -27,6 +57,7 @@ var WorkerTransport = class {
|
|
|
27
57
|
this.bufferSize = config.bufferSize ?? 1e3;
|
|
28
58
|
this.maxRestarts = config.maxRestarts ?? 3;
|
|
29
59
|
this.level = config.level;
|
|
60
|
+
require_secret_config.protectSecrets(this, ["config"]);
|
|
30
61
|
this.startWorker();
|
|
31
62
|
}
|
|
32
63
|
startWorker() {
|
|
@@ -157,12 +188,11 @@ var WorkerTransport = class {
|
|
|
157
188
|
}
|
|
158
189
|
}
|
|
159
190
|
};
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
return WorkerTransport;
|
|
166
|
-
}
|
|
191
|
+
Object.defineProperty(exports, "WorkerTransport", {
|
|
192
|
+
enumerable: true,
|
|
193
|
+
get: function() {
|
|
194
|
+
return WorkerTransport;
|
|
195
|
+
}
|
|
167
196
|
});
|
|
168
|
-
|
|
197
|
+
|
|
198
|
+
//# sourceMappingURL=worker.transport-C6GNl_r2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker.transport-C6GNl_r2.js","names":["Worker","path"],"sources":["../src/transports/worker.transport.ts"],"sourcesContent":["/**\n * logixia — Worker Thread Transport\n *\n * Offloads JSON serialization and all I/O to a Node.js worker thread,\n * completely eliminating any event-loop impact from logging. The main thread\n * only posts a raw message to the worker — it never calls JSON.stringify or\n * any I/O syscalls on the hot path.\n *\n * Architecture:\n * Main thread → MessageChannel → Worker thread → Wrapped transport\n *\n * The worker runs an ordinary logixia transport (file, database, console…)\n * inside its own event loop. If the worker crashes it is restarted automatically\n * (up to `maxRestarts` times) and buffered messages are replayed.\n *\n * @example\n * ```ts\n * import { WorkerTransport } from 'logixia/worker';\n *\n * const logger = createLogger({\n * transports: {\n * // Run file transport inside a worker thread — zero event-loop impact\n * worker: new WorkerTransport({\n * transportType: 'file',\n * transportConfig: { filename: 'app.log', dirname: './logs' },\n * bufferSize: 500,\n * maxRestarts: 3,\n * }),\n * },\n * });\n * ```\n */\n\nimport path from 'node:path';\nimport { Worker } from 'node:worker_threads';\n\nimport type { ITransport, TransportLogEntry } from '../types/transport.types';\nimport { internalError, internalWarn } from '../utils/internal-log';\nimport { protectSecrets } from './secret-config';\n\nexport interface WorkerTransportConfig {\n /**\n * Which built-in logixia transport to run inside the worker thread.\n * The worker resolves the correct module automatically.\n */\n transportType: 'file' | 'database' | 'console';\n /** Config forwarded verbatim to the wrapped transport constructor. */\n transportConfig: Record<string, unknown>;\n /**\n * Max log entries to buffer in the main thread while the worker is starting\n * or restarting. Entries beyond this limit are dropped with a warning.\n * @default 1000\n */\n bufferSize?: number;\n /**\n * How many times to restart the worker if it crashes unexpectedly.\n * @default 3\n */\n maxRestarts?: number;\n /**\n * Log level filter — only entries at or above this level are forwarded.\n * Useful for routing only errors to an expensive transport in a worker.\n */\n level?: string;\n}\n\n/**\n * Transport that runs a wrapped transport inside a dedicated Node.js worker\n * thread, completely removing JSON serialization and I/O from the main event loop.\n */\nexport class WorkerTransport implements ITransport {\n public readonly name = 'worker';\n public readonly level: string | undefined;\n public readonly batchSize = 1;\n public readonly flushInterval = 0;\n\n private worker: Worker | null = null;\n private ready = false;\n private readonly buffer: TransportLogEntry[] = [];\n private readonly bufferSize: number;\n private restarts = 0;\n private readonly maxRestarts: number;\n private readonly config: WorkerTransportConfig;\n /** Pending restart-backoff timer, so close() can cancel a queued restart. */\n private restartTimer: NodeJS.Timeout | null = null;\n /** Set once close() begins, so a worker 'exit' no longer triggers a restart. */\n private closing = false;\n /** Max time to wait for the worker's 'flushed' ack before giving up. */\n private readonly FLUSH_TIMEOUT_MS = 5000;\n /** Max time to wait for a graceful worker exit before force-terminating. */\n private readonly SHUTDOWN_TIMEOUT_MS = 5000;\n\n constructor(config: WorkerTransportConfig) {\n this.config = config;\n this.bufferSize = config.bufferSize ?? 1000;\n this.maxRestarts = config.maxRestarts ?? 3;\n this.level = config.level;\n protectSecrets(this, ['config']);\n this.startWorker();\n }\n\n private startWorker(): void {\n try {\n this.worker = new Worker(this.workerFile(), {\n workerData: {\n transportType: this.config.transportType,\n transportConfig: this.config.transportConfig,\n },\n });\n\n this.worker.on('message', (msg: { type: string; error?: string }) => {\n if (msg.type === 'ready') {\n this.ready = true;\n this.drainBuffer();\n } else if (msg.type === 'error' || msg.type === 'write-error') {\n internalError(\n `WorkerTransport [${this.config.transportType}]: ${msg.error ?? 'unknown'}`\n );\n }\n });\n\n this.worker.on('error', (err) => {\n internalError('WorkerTransport worker error', err);\n this.handleWorkerExit();\n });\n\n this.worker.on('exit', (code) => {\n if (code !== 0) {\n internalWarn(`WorkerTransport worker exited with code ${code}`);\n this.handleWorkerExit();\n }\n });\n } catch (err) {\n internalError('WorkerTransport failed to start', err);\n }\n }\n\n /** The worker entry is always built as CommonJS, next to this module's output. */\n protected workerFile(): string {\n return path.join(__dirname, 'worker-entry.js');\n }\n\n private handleWorkerExit(): void {\n this.ready = false;\n // Don't resurrect a worker we're intentionally shutting down — close() sets\n // `closing` and nulls the worker, so a late 'exit'/'error' event must not\n // queue a restart (which would spawn a fresh leaked thread post-shutdown).\n if (this.closing) return;\n if (this.restarts < this.maxRestarts) {\n this.restarts++;\n internalWarn(`WorkerTransport restarting (attempt ${this.restarts}/${this.maxRestarts})`);\n // Small backoff before restart. unref() so a perpetually-failing worker's\n // pending restart never keeps the process alive on its own.\n this.restartTimer = setTimeout(() => {\n this.restartTimer = null;\n this.startWorker();\n }, 500 * this.restarts);\n if (this.restartTimer.unref) this.restartTimer.unref();\n } else {\n internalError(\n `WorkerTransport exhausted ${this.maxRestarts} restart attempts — transport disabled`\n );\n }\n }\n\n private drainBuffer(): void {\n while (this.buffer.length > 0 && this.ready && this.worker) {\n const entry = this.buffer.shift();\n if (entry) {\n this.worker.postMessage({ type: 'write', entry });\n }\n }\n }\n\n write(entry: TransportLogEntry): void {\n if (this.ready && this.worker) {\n this.worker.postMessage({ type: 'write', entry });\n } else {\n if (this.buffer.length >= this.bufferSize) {\n internalWarn('WorkerTransport buffer full — dropping oldest entry');\n this.buffer.shift();\n }\n this.buffer.push(entry);\n }\n }\n\n async flush(): Promise<void> {\n if (!this.ready || !this.worker) return;\n const worker = this.worker;\n return new Promise<void>((resolve) => {\n // Time-box the flush: if the worker dies or restarts before answering,\n // the 'flushed' message would never arrive and this promise would hang\n // forever, blocking shutdown until the force-exit timer kills the process\n // (losing everything). Resolve on timeout so close() can still terminate.\n const timer = setTimeout(() => {\n worker.off('message', handler);\n resolve();\n }, this.FLUSH_TIMEOUT_MS);\n if (timer.unref) timer.unref();\n\n const handler = (msg: { type: string }) => {\n if (msg.type === 'flushed') {\n clearTimeout(timer);\n worker.off('message', handler);\n resolve();\n }\n };\n worker.on('message', handler);\n worker.postMessage({ type: 'flush' });\n });\n }\n\n /**\n * Flush the worker's buffer and terminate the thread on shutdown.\n *\n * This MUST be named close() — TransportManager.close() invokes\n * transport.close(), so a method named only shutdown() was never called on\n * graceful exit, leaking the worker thread and dropping its buffered logs.\n */\n async close(): Promise<void> {\n // Stop the restart loop first: cancel any queued backoff restart and flag\n // that further worker exits are expected (so handleWorkerExit no-ops).\n this.closing = true;\n if (this.restartTimer) {\n clearTimeout(this.restartTimer);\n this.restartTimer = null;\n }\n\n if (!this.worker) return;\n const worker = this.worker;\n this.worker = null;\n\n // Push any locally-buffered (pre-ready) entries first: the worker's port\n // queues them until its listener attaches, so they are handled before the\n // shutdown message, which flushes the wrapped transport and exits.\n this.drainBufferTo(worker);\n worker.postMessage({ type: 'shutdown' });\n\n await new Promise<void>((resolve) => {\n // Don't wait forever for a wedged worker — terminate() it after a timeout.\n const timer = setTimeout(() => {\n worker.terminate().finally(() => resolve());\n }, this.SHUTDOWN_TIMEOUT_MS);\n if (timer.unref) timer.unref();\n\n worker.once('exit', () => {\n clearTimeout(timer);\n resolve();\n });\n });\n }\n\n /** Back-compat alias — prefer close(). */\n async shutdown(): Promise<void> {\n await this.close();\n }\n\n private drainBufferTo(worker: Worker): void {\n while (this.buffer.length > 0) {\n const entry = this.buffer.shift();\n if (entry) worker.postMessage({ type: 'write', entry });\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA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AAC;EACtC,CAAC;CACH;;;;;;;;CASA,MAAM,QAAuB;EAG3B,KAAK,UAAU;EACf,IAAI,KAAK,cAAc;GACrB,aAAa,KAAK,YAAY;GAC9B,KAAK,eAAe;EACtB;EAEA,IAAI,CAAC,KAAK,QAAQ;EAClB,MAAM,SAAS,KAAK;EACpB,KAAK,SAAS;EAKd,KAAK,cAAc,MAAM;EACzB,OAAO,YAAY,EAAE,MAAM,WAAW,CAAC;EAEvC,MAAM,IAAI,SAAe,YAAY;GAEnC,MAAM,QAAQ,iBAAiB;IAC7B,OAAO,UAAU,CAAC,CAAC,cAAc,QAAQ,CAAC;GAC5C,GAAG,KAAK,mBAAmB;GAC3B,IAAI,MAAM,OAAO,MAAM,MAAM;GAE7B,OAAO,KAAK,cAAc;IACxB,aAAa,KAAK;IAClB,QAAQ;GACV,CAAC;EACH,CAAC;CACH;;CAGA,MAAM,WAA0B;EAC9B,MAAM,KAAK,MAAM;CACnB;CAEA,cAAsB,QAAsB;EAC1C,OAAO,KAAK,OAAO,SAAS,GAAG;GAC7B,MAAM,QAAQ,KAAK,OAAO,MAAM;GAChC,IAAI,OAAO,OAAO,YAAY;IAAE,MAAM;IAAS;GAAM,CAAC;EACxD;CACF;AACF"}
|
|
@@ -1,15 +1,45 @@
|
|
|
1
|
-
import { r as internalWarn, t as internalError } from "./internal-log-
|
|
1
|
+
import { r as internalWarn, t as internalError } from "./internal-log-uCSd1PMc.mjs";
|
|
2
|
+
import { n as protectSecrets } from "./secret-config-BegMLkYl.mjs";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import { fileURLToPath } from "node:url";
|
|
4
5
|
import { Worker } from "node:worker_threads";
|
|
5
|
-
|
|
6
|
-
//#region node_modules/tsdown/esm-shims.js
|
|
6
|
+
// node_modules/tsdown/esm-shims.js
|
|
7
7
|
const getFilename = () => fileURLToPath(import.meta.url);
|
|
8
8
|
const getDirname = () => path.dirname(getFilename());
|
|
9
9
|
const __dirname = /* @__PURE__ */ getDirname();
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
// src/transports/worker.transport.ts
|
|
11
|
+
/**
|
|
12
|
+
* logixia — Worker Thread Transport
|
|
13
|
+
*
|
|
14
|
+
* Offloads JSON serialization and all I/O to a Node.js worker thread,
|
|
15
|
+
* completely eliminating any event-loop impact from logging. The main thread
|
|
16
|
+
* only posts a raw message to the worker — it never calls JSON.stringify or
|
|
17
|
+
* any I/O syscalls on the hot path.
|
|
18
|
+
*
|
|
19
|
+
* Architecture:
|
|
20
|
+
* Main thread → MessageChannel → Worker thread → Wrapped transport
|
|
21
|
+
*
|
|
22
|
+
* The worker runs an ordinary logixia transport (file, database, console…)
|
|
23
|
+
* inside its own event loop. If the worker crashes it is restarted automatically
|
|
24
|
+
* (up to `maxRestarts` times) and buffered messages are replayed.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* import { WorkerTransport } from 'logixia/worker';
|
|
29
|
+
*
|
|
30
|
+
* const logger = createLogger({
|
|
31
|
+
* transports: {
|
|
32
|
+
* // Run file transport inside a worker thread — zero event-loop impact
|
|
33
|
+
* worker: new WorkerTransport({
|
|
34
|
+
* transportType: 'file',
|
|
35
|
+
* transportConfig: { filename: 'app.log', dirname: './logs' },
|
|
36
|
+
* bufferSize: 500,
|
|
37
|
+
* maxRestarts: 3,
|
|
38
|
+
* }),
|
|
39
|
+
* },
|
|
40
|
+
* });
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
13
43
|
/**
|
|
14
44
|
* Transport that runs a wrapped transport inside a dedicated Node.js worker
|
|
15
45
|
* thread, completely removing JSON serialization and I/O from the main event loop.
|
|
@@ -31,6 +61,7 @@ var WorkerTransport = class {
|
|
|
31
61
|
this.bufferSize = config.bufferSize ?? 1e3;
|
|
32
62
|
this.maxRestarts = config.maxRestarts ?? 3;
|
|
33
63
|
this.level = config.level;
|
|
64
|
+
protectSecrets(this, ["config"]);
|
|
34
65
|
this.startWorker();
|
|
35
66
|
}
|
|
36
67
|
startWorker() {
|
|
@@ -161,7 +192,6 @@ var WorkerTransport = class {
|
|
|
161
192
|
}
|
|
162
193
|
}
|
|
163
194
|
};
|
|
164
|
-
|
|
165
|
-
//#endregion
|
|
166
195
|
export { WorkerTransport as t };
|
|
167
|
-
|
|
196
|
+
|
|
197
|
+
//# sourceMappingURL=worker.transport-DLVA4y2e.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker.transport-DLVA4y2e.mjs","names":[],"sources":["../node_modules/tsdown/esm-shims.js","../src/transports/worker.transport.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * logixia — Worker Thread Transport\n *\n * Offloads JSON serialization and all I/O to a Node.js worker thread,\n * completely eliminating any event-loop impact from logging. The main thread\n * only posts a raw message to the worker — it never calls JSON.stringify or\n * any I/O syscalls on the hot path.\n *\n * Architecture:\n * Main thread → MessageChannel → Worker thread → Wrapped transport\n *\n * The worker runs an ordinary logixia transport (file, database, console…)\n * inside its own event loop. If the worker crashes it is restarted automatically\n * (up to `maxRestarts` times) and buffered messages are replayed.\n *\n * @example\n * ```ts\n * import { WorkerTransport } from 'logixia/worker';\n *\n * const logger = createLogger({\n * transports: {\n * // Run file transport inside a worker thread — zero event-loop impact\n * worker: new WorkerTransport({\n * transportType: 'file',\n * transportConfig: { filename: 'app.log', dirname: './logs' },\n * bufferSize: 500,\n * maxRestarts: 3,\n * }),\n * },\n * });\n * ```\n */\n\nimport path from 'node:path';\nimport { Worker } from 'node:worker_threads';\n\nimport type { ITransport, TransportLogEntry } from '../types/transport.types';\nimport { internalError, internalWarn } from '../utils/internal-log';\nimport { protectSecrets } from './secret-config';\n\nexport interface WorkerTransportConfig {\n /**\n * Which built-in logixia transport to run inside the worker thread.\n * The worker resolves the correct module automatically.\n */\n transportType: 'file' | 'database' | 'console';\n /** Config forwarded verbatim to the wrapped transport constructor. */\n transportConfig: Record<string, unknown>;\n /**\n * Max log entries to buffer in the main thread while the worker is starting\n * or restarting. Entries beyond this limit are dropped with a warning.\n * @default 1000\n */\n bufferSize?: number;\n /**\n * How many times to restart the worker if it crashes unexpectedly.\n * @default 3\n */\n maxRestarts?: number;\n /**\n * Log level filter — only entries at or above this level are forwarded.\n * Useful for routing only errors to an expensive transport in a worker.\n */\n level?: string;\n}\n\n/**\n * Transport that runs a wrapped transport inside a dedicated Node.js worker\n * thread, completely removing JSON serialization and I/O from the main event loop.\n */\nexport class WorkerTransport implements ITransport {\n public readonly name = 'worker';\n public readonly level: string | undefined;\n public readonly batchSize = 1;\n public readonly flushInterval = 0;\n\n private worker: Worker | null = null;\n private ready = false;\n private readonly buffer: TransportLogEntry[] = [];\n private readonly bufferSize: number;\n private restarts = 0;\n private readonly maxRestarts: number;\n private readonly config: WorkerTransportConfig;\n /** Pending restart-backoff timer, so close() can cancel a queued restart. */\n private restartTimer: NodeJS.Timeout | null = null;\n /** Set once close() begins, so a worker 'exit' no longer triggers a restart. */\n private closing = false;\n /** Max time to wait for the worker's 'flushed' ack before giving up. */\n private readonly FLUSH_TIMEOUT_MS = 5000;\n /** Max time to wait for a graceful worker exit before force-terminating. */\n private readonly SHUTDOWN_TIMEOUT_MS = 5000;\n\n constructor(config: WorkerTransportConfig) {\n this.config = config;\n this.bufferSize = config.bufferSize ?? 1000;\n this.maxRestarts = config.maxRestarts ?? 3;\n this.level = config.level;\n protectSecrets(this, ['config']);\n this.startWorker();\n }\n\n private startWorker(): void {\n try {\n this.worker = new Worker(this.workerFile(), {\n workerData: {\n transportType: this.config.transportType,\n transportConfig: this.config.transportConfig,\n },\n });\n\n this.worker.on('message', (msg: { type: string; error?: string }) => {\n if (msg.type === 'ready') {\n this.ready = true;\n this.drainBuffer();\n } else if (msg.type === 'error' || msg.type === 'write-error') {\n internalError(\n `WorkerTransport [${this.config.transportType}]: ${msg.error ?? 'unknown'}`\n );\n }\n });\n\n this.worker.on('error', (err) => {\n internalError('WorkerTransport worker error', err);\n this.handleWorkerExit();\n });\n\n this.worker.on('exit', (code) => {\n if (code !== 0) {\n internalWarn(`WorkerTransport worker exited with code ${code}`);\n this.handleWorkerExit();\n }\n });\n } catch (err) {\n internalError('WorkerTransport failed to start', err);\n }\n }\n\n /** The worker entry is always built as CommonJS, next to this module's output. */\n protected workerFile(): string {\n return path.join(__dirname, 'worker-entry.js');\n }\n\n private handleWorkerExit(): void {\n this.ready = false;\n // Don't resurrect a worker we're intentionally shutting down — close() sets\n // `closing` and nulls the worker, so a late 'exit'/'error' event must not\n // queue a restart (which would spawn a fresh leaked thread post-shutdown).\n if (this.closing) return;\n if (this.restarts < this.maxRestarts) {\n this.restarts++;\n internalWarn(`WorkerTransport restarting (attempt ${this.restarts}/${this.maxRestarts})`);\n // Small backoff before restart. unref() so a perpetually-failing worker's\n // pending restart never keeps the process alive on its own.\n this.restartTimer = setTimeout(() => {\n this.restartTimer = null;\n this.startWorker();\n }, 500 * this.restarts);\n if (this.restartTimer.unref) this.restartTimer.unref();\n } else {\n internalError(\n `WorkerTransport exhausted ${this.maxRestarts} restart attempts — transport disabled`\n );\n }\n }\n\n private drainBuffer(): void {\n while (this.buffer.length > 0 && this.ready && this.worker) {\n const entry = this.buffer.shift();\n if (entry) {\n this.worker.postMessage({ type: 'write', entry });\n }\n }\n }\n\n write(entry: TransportLogEntry): void {\n if (this.ready && this.worker) {\n this.worker.postMessage({ type: 'write', entry });\n } else {\n if (this.buffer.length >= this.bufferSize) {\n internalWarn('WorkerTransport buffer full — dropping oldest entry');\n this.buffer.shift();\n }\n this.buffer.push(entry);\n }\n }\n\n async flush(): Promise<void> {\n if (!this.ready || !this.worker) return;\n const worker = this.worker;\n return new Promise<void>((resolve) => {\n // Time-box the flush: if the worker dies or restarts before answering,\n // the 'flushed' message would never arrive and this promise would hang\n // forever, blocking shutdown until the force-exit timer kills the process\n // (losing everything). Resolve on timeout so close() can still terminate.\n const timer = setTimeout(() => {\n worker.off('message', handler);\n resolve();\n }, this.FLUSH_TIMEOUT_MS);\n if (timer.unref) timer.unref();\n\n const handler = (msg: { type: string }) => {\n if (msg.type === 'flushed') {\n clearTimeout(timer);\n worker.off('message', handler);\n resolve();\n }\n };\n worker.on('message', handler);\n worker.postMessage({ type: 'flush' });\n });\n }\n\n /**\n * Flush the worker's buffer and terminate the thread on shutdown.\n *\n * This MUST be named close() — TransportManager.close() invokes\n * transport.close(), so a method named only shutdown() was never called on\n * graceful exit, leaking the worker thread and dropping its buffered logs.\n */\n async close(): Promise<void> {\n // Stop the restart loop first: cancel any queued backoff restart and flag\n // that further worker exits are expected (so handleWorkerExit no-ops).\n this.closing = true;\n if (this.restartTimer) {\n clearTimeout(this.restartTimer);\n this.restartTimer = null;\n }\n\n if (!this.worker) return;\n const worker = this.worker;\n this.worker = null;\n\n // Push any locally-buffered (pre-ready) entries first: the worker's port\n // queues them until its listener attaches, so they are handled before the\n // shutdown message, which flushes the wrapped transport and exits.\n this.drainBufferTo(worker);\n worker.postMessage({ type: 'shutdown' });\n\n await new Promise<void>((resolve) => {\n // Don't wait forever for a wedged worker — terminate() it after a timeout.\n const timer = setTimeout(() => {\n worker.terminate().finally(() => resolve());\n }, this.SHUTDOWN_TIMEOUT_MS);\n if (timer.unref) timer.unref();\n\n worker.once('exit', () => {\n clearTimeout(timer);\n resolve();\n });\n });\n }\n\n /** Back-compat alias — prefer close(). */\n async shutdown(): Promise<void> {\n await this.close();\n }\n\n private drainBufferTo(worker: Worker): void {\n while (this.buffer.length > 0) {\n const entry = this.buffer.shift();\n if (entry) worker.postMessage({ type: 'write', entry });\n }\n }\n}\n"],"ignoreList":[0],"mappings":";;;;;;AAIA,MAAM,oBAAoB,cAAc,YAAY,GAAG;AACvD,MAAM,mBAAmB,KAAK,QAAQ,YAAY,CAAC;AAEnD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C;EACtC,CAAC;CACH;;;;;;;;CASA,MAAM,QAAuB;EAG3B,KAAK,UAAU;EACf,IAAI,KAAK,cAAc;GACrB,aAAa,KAAK,YAAY;GAC9B,KAAK,eAAe;EACtB;EAEA,IAAI,CAAC,KAAK,QAAQ;EAClB,MAAM,SAAS,KAAK;EACpB,KAAK,SAAS;EAKd,KAAK,cAAc,MAAM;EACzB,OAAO,YAAY,EAAE,MAAM,WAAW,CAAC;EAEvC,MAAM,IAAI,SAAe,YAAY;GAEnC,MAAM,QAAQ,iBAAiB;IAC7B,OAAO,UAAU,CAAC,CAAC,cAAc,QAAQ,CAAC;GAC5C,GAAG,KAAK,mBAAmB;GAC3B,IAAI,MAAM,OAAO,MAAM,MAAM;GAE7B,OAAO,KAAK,cAAc;IACxB,aAAa,KAAK;IAClB,QAAQ;GACV,CAAC;EACH,CAAC;CACH;;CAGA,MAAM,WAA0B;EAC9B,MAAM,KAAK,MAAM;CACnB;CAEA,cAAsB,QAAsB;EAC1C,OAAO,KAAK,OAAO,SAAS,GAAG;GAC7B,MAAM,QAAQ,KAAK,OAAO,MAAM;GAChC,IAAI,OAAO,OAAO,YAAY;IAAE,MAAM;IAAS;GAAM,CAAC;EACxD;CACF;AACF"}
|
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
import { l as ITransport, p as TransportLogEntry } from "./transport.types-
|
|
2
|
-
|
|
3
|
-
//#region src/transports/worker.transport.d.ts
|
|
4
|
-
|
|
1
|
+
import { l as ITransport, p as TransportLogEntry } from "./transport.types-BJVL1QQl.mjs";
|
|
5
2
|
interface WorkerTransportConfig {
|
|
6
3
|
/**
|
|
7
4
|
* Which built-in logixia transport to run inside the worker thread.
|
|
@@ -71,6 +68,5 @@ declare class WorkerTransport implements ITransport {
|
|
|
71
68
|
shutdown(): Promise<void>;
|
|
72
69
|
private drainBufferTo;
|
|
73
70
|
}
|
|
74
|
-
//#endregion
|
|
75
71
|
export { WorkerTransportConfig as n, WorkerTransport as t };
|
|
76
|
-
//# sourceMappingURL=worker.transport-
|
|
72
|
+
//# sourceMappingURL=worker.transport-hJay1wxA.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker.transport-hJay1wxA.d.mts","names":[],"sources":["../src/transports/worker.transport.ts"],"mappings":";UAwCiB;;;;;EAKf;;EAEA,iBAAiB;;;;;;EAMjB;;;;;EAKA;;;;;EAKA;;;;;;cAOW,2BAA2B;WACtB;WACA;WACA;WACA;UAER;UACA;mBACS;mBACA;UACT;mBACS;mBACA;;UAET;;UAEA;;mBAES;;mBAEA;EAEL,YAAA,QAAQ;UASZ;;YAqCE;UAIF;UAuBA;EASR,MAAM,OAAO;EAYP,SAAS;;;;;;;;EAiCT,SAAS;;EAkCT,YAAY;UAIV"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "logixia",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.4",
|
|
4
4
|
"description": "Async-first TypeScript logger: wide events / canonical log lines, OTLP OpenTelemetry export, runtime log levels, redaction, adaptive sampling, NestJS, multi-transport (file, DB, cloud), tracing & log search. A fast Winston/Pino alternative.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -151,6 +151,7 @@
|
|
|
151
151
|
"format:check": "prettier --check .",
|
|
152
152
|
"typecheck": "tsc --noEmit",
|
|
153
153
|
"typecheck:examples": "tsc -p tsconfig.examples.json && tsc -p examples/cloudflare-worker/tsconfig.json",
|
|
154
|
+
"typecheck:express4": "node scripts/typecheck-express4.mjs",
|
|
154
155
|
"check": "npm run typecheck && npm run lint:check",
|
|
155
156
|
"ci": "npm run typecheck && npm run lint:check && npm run test:ci",
|
|
156
157
|
"validate": "npm run clean && npm run build && npm run typecheck && npm run lint:check && npm run test:coverage",
|
|
@@ -165,8 +166,10 @@
|
|
|
165
166
|
"dev:performance": "ts-node -P tsconfig.examples.json --transpile-only -r ./examples/register.js examples/performance-monitoring.ts",
|
|
166
167
|
"dev:fields": "ts-node -P tsconfig.examples.json --transpile-only -r ./examples/register.js examples/field-configuration.ts",
|
|
167
168
|
"dev:search": "ts-node -P tsconfig.examples.json --transpile-only -r ./examples/register.js examples/search-quickstart.ts",
|
|
169
|
+
"dev:search-readme": "ts-node -P tsconfig.examples.json --transpile-only -r ./examples/register.js examples/search-readme.ts",
|
|
168
170
|
"dev:intelligent-search": "ts-node -P tsconfig.examples.json --transpile-only -r ./examples/register.js examples/intelligent-search.ts",
|
|
169
171
|
"benchmark": "npm run build && node benchmarks/run.mjs",
|
|
172
|
+
"check:browser": "node --experimental-vm-modules --no-warnings scripts/check-browser-entry.mjs",
|
|
170
173
|
"check:exports": "node scripts/check-exports.mjs",
|
|
171
174
|
"check:optional-peers": "node scripts/check-optional-peers.mjs",
|
|
172
175
|
"size": "size-limit",
|
|
@@ -311,18 +314,17 @@
|
|
|
311
314
|
"@semantic-release/github": "12.0.10",
|
|
312
315
|
"@semantic-release/npm": "13.2.0",
|
|
313
316
|
"@semantic-release/release-notes-generator": "14.1.1",
|
|
314
|
-
"@size-limit/file": "^
|
|
315
|
-
"@types/express": "^
|
|
317
|
+
"@size-limit/file": "^14.3.0",
|
|
318
|
+
"@types/express": "^5.0.6",
|
|
316
319
|
"@types/jest": "^30.0.0",
|
|
317
|
-
"@types/node": "^20.
|
|
320
|
+
"@types/node": "^20.19.43",
|
|
318
321
|
"@types/pg": "^8.15.5",
|
|
319
|
-
"@types/pino": "^7.0.4",
|
|
320
322
|
"conventional-changelog-conventionalcommits": "8.0.0",
|
|
321
323
|
"eslint": "^10.0.3",
|
|
322
324
|
"eslint-config-prettier": "^10.1.8",
|
|
323
|
-
"eslint-plugin-simple-import-sort": "^
|
|
324
|
-
"eslint-plugin-sonarjs": "4.2.
|
|
325
|
-
"eslint-plugin-unicorn": "^
|
|
325
|
+
"eslint-plugin-simple-import-sort": "^14.0.0",
|
|
326
|
+
"eslint-plugin-sonarjs": "^4.2.2",
|
|
327
|
+
"eslint-plugin-unicorn": "^78.0.0",
|
|
326
328
|
"express": "^5.2.1",
|
|
327
329
|
"fastify": "^5.12.7",
|
|
328
330
|
"globals": "^17.4.0",
|
|
@@ -338,20 +340,26 @@
|
|
|
338
340
|
"prettier": "^3.8.1",
|
|
339
341
|
"reflect-metadata": "^0.2.2",
|
|
340
342
|
"semantic-release": "25.0.9",
|
|
341
|
-
"size-limit": "^
|
|
343
|
+
"size-limit": "^14.3.0",
|
|
342
344
|
"socket.io": "^4.8.3",
|
|
343
345
|
"tinybench": "^6.0.0",
|
|
344
346
|
"ts-jest": "^29.0.0",
|
|
345
347
|
"ts-node": "^10.9.2",
|
|
346
|
-
"tsdown": "^0.
|
|
348
|
+
"tsdown": "^0.23.1",
|
|
347
349
|
"typescript": "^5.0.0",
|
|
348
350
|
"typescript-eslint": "^8.57.0",
|
|
349
|
-
"uuid": "^11.1.1",
|
|
350
351
|
"winston": "^3.19.0"
|
|
351
352
|
},
|
|
352
353
|
"engines": {
|
|
353
354
|
"node": ">=16.0.0"
|
|
354
355
|
},
|
|
356
|
+
"devEngines": {
|
|
357
|
+
"runtime": {
|
|
358
|
+
"name": "node",
|
|
359
|
+
"version": "^22.19.0 || ^24.11.0 || >=26.0.0",
|
|
360
|
+
"onFail": "warn"
|
|
361
|
+
}
|
|
362
|
+
},
|
|
355
363
|
"bin": {
|
|
356
364
|
"logixia": "./dist/cli/index.js"
|
|
357
365
|
},
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
import { d as sanitizeIncomingId } from "./trace.utils-CvXgaiQT.mjs";
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
|
-
|
|
5
|
-
//#region src/context/async-context.ts
|
|
6
|
-
/** Generates an 8-character random ID using Node's crypto module. */
|
|
7
|
-
function randomShortId() {
|
|
8
|
-
return randomUUID().slice(0, 8);
|
|
9
|
-
}
|
|
10
|
-
const _storage = new AsyncLocalStorage();
|
|
11
|
-
const LogixiaContext = {
|
|
12
|
-
run(store, callback) {
|
|
13
|
-
const parent = _storage.getStore() ?? {};
|
|
14
|
-
return _storage.run({
|
|
15
|
-
...parent,
|
|
16
|
-
...store
|
|
17
|
-
}, callback);
|
|
18
|
-
},
|
|
19
|
-
get() {
|
|
20
|
-
return _storage.getStore();
|
|
21
|
-
},
|
|
22
|
-
set(fields) {
|
|
23
|
-
const store = _storage.getStore();
|
|
24
|
-
if (!store) return;
|
|
25
|
-
for (const key of Object.keys(fields)) {
|
|
26
|
-
if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
|
|
27
|
-
store[key] = fields[key];
|
|
28
|
-
}
|
|
29
|
-
},
|
|
30
|
-
getStorage() {
|
|
31
|
-
return _storage;
|
|
32
|
-
}
|
|
33
|
-
};
|
|
34
|
-
/**
|
|
35
|
-
* Create an Express/Connect-compatible middleware that wraps each request in
|
|
36
|
-
* a `LogixiaContext.run()` scope populated with common request fields.
|
|
37
|
-
*
|
|
38
|
-
* @example
|
|
39
|
-
* ```ts
|
|
40
|
-
* import { createExpressContextMiddleware } from 'logixia';
|
|
41
|
-
* app.use(createExpressContextMiddleware());
|
|
42
|
-
* ```
|
|
43
|
-
*/
|
|
44
|
-
function createExpressContextMiddleware(options = {}) {
|
|
45
|
-
const { enrich, traceIdHeader = "x-trace-id" } = options;
|
|
46
|
-
return function logixiaContextMiddleware(req, _res, next) {
|
|
47
|
-
const base = { traceId: sanitizeIncomingId((req["headers"] ?? {})[traceIdHeader.toLowerCase()]) ?? randomShortId() };
|
|
48
|
-
LogixiaContext.run({
|
|
49
|
-
...base,
|
|
50
|
-
...enrich ? enrich(req) : {}
|
|
51
|
-
}, next);
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* Create a Fastify lifecycle hook that wraps each request in a context scope.
|
|
56
|
-
*
|
|
57
|
-
* Register with `fastify.addHook('onRequest', createFastifyContextHook())`.
|
|
58
|
-
*/
|
|
59
|
-
function createFastifyContextHook(options = {}) {
|
|
60
|
-
const { enrich, traceIdHeader = "x-trace-id" } = options;
|
|
61
|
-
return function logixiaFastifyHook(request, _reply, done) {
|
|
62
|
-
const base = { traceId: sanitizeIncomingId((request["headers"] ?? {})[traceIdHeader.toLowerCase()]) ?? sanitizeIncomingId(request["id"]) ?? randomShortId() };
|
|
63
|
-
LogixiaContext.run({
|
|
64
|
-
...base,
|
|
65
|
-
...enrich ? enrich(request) : {}
|
|
66
|
-
}, done);
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
//#endregion
|
|
71
|
-
export { createExpressContextMiddleware as n, createFastifyContextHook as r, LogixiaContext as t };
|
|
72
|
-
//# sourceMappingURL=async-context-BzJrbfQs.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"async-context-BzJrbfQs.mjs","names":["base: LogContext"],"sources":["../src/context/async-context.ts"],"sourcesContent":["/**\n * LogixiaContext — Zero-boilerplate AsyncLocalStorage context propagation.\n *\n * Lets every `logger.info()` call inside a context automatically pick up stored\n * fields (requestId, userId, tenantId, …) without passing them through every function.\n *\n * Works across `Promise.all`, `setTimeout`, and event emitters — anything that\n * inherits the async execution context.\n *\n * @example\n * ```ts\n * import { LogixiaContext } from 'logixia';\n *\n * // Wrap a request handler:\n * app.use((req, res, next) => {\n * LogixiaContext.run({ requestId: req.id, userId: req.user?.id }, next);\n * });\n *\n * // Anywhere deeper in the call tree:\n * async function processOrder(orderId: string) {\n * const ctx = LogixiaContext.get(); // { requestId, userId, orderId }\n * logger.info('Processing order', { orderId, ...ctx });\n * }\n * ```\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { randomUUID } from 'node:crypto';\n\nimport { sanitizeIncomingId } from '../utils/trace.utils';\n\n/** Generates an 8-character random ID using Node's crypto module. */\nfunction randomShortId(): string {\n return randomUUID().slice(0, 8);\n}\n\nexport interface LogContext {\n traceId?: string;\n spanId?: string;\n userId?: string;\n tenantId?: string;\n sessionId?: string;\n [key: string]: unknown;\n}\n\n// Module-level singleton so all loggers share the same ALS store.\nconst _storage = new AsyncLocalStorage<LogContext>();\n\nexport const LogixiaContext = {\n /**\n * Run `callback` inside an async context that carries `store` fields.\n * All loggers queried within `callback` (and its async descendants) will\n * automatically see these fields.\n *\n * @example\n * ```ts\n * LogixiaContext.run({ requestId: 'abc', userId: '42' }, async () => {\n * await processOrder(); // sees requestId + userId in every log\n * });\n * ```\n */\n run<T>(store: LogContext, callback: () => T): T {\n const parent = _storage.getStore() ?? {};\n return _storage.run({ ...parent, ...store }, callback);\n },\n\n /**\n * Return the context fields active in the current async scope.\n * Returns `undefined` when called outside any `LogixiaContext.run()`.\n */\n get(): LogContext | undefined {\n return _storage.getStore();\n },\n\n /**\n * Merge `fields` into the **existing** context for the current scope.\n * If called outside a `run()` context this is a no-op (logs a dev warning).\n */\n set(fields: Partial<LogContext>): void {\n const store = _storage.getStore();\n if (!store) {\n // Silently ignore — avoids crashing in code that may call setContext\n // before a request context is established (e.g. background jobs).\n return;\n }\n for (const key of Object.keys(fields)) {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;\n store[key] = fields[key];\n }\n },\n\n /**\n * Retrieve the underlying `AsyncLocalStorage` instance.\n * Useful for advanced use-cases like custom middleware.\n */\n getStorage(): AsyncLocalStorage<LogContext> {\n return _storage;\n },\n};\n\n/**\n * Create an Express/Connect-compatible middleware that wraps each request in\n * a `LogixiaContext.run()` scope populated with common request fields.\n *\n * @example\n * ```ts\n * import { createExpressContextMiddleware } from 'logixia';\n * app.use(createExpressContextMiddleware());\n * ```\n */\nexport function createExpressContextMiddleware(\n options: {\n /** Extract additional fields from the request. */\n enrich?: (req: Record<string, unknown>) => Partial<LogContext>;\n /** Header to read the traceId from. Default: 'x-trace-id'. */\n traceIdHeader?: string;\n } = {}\n) {\n const { enrich, traceIdHeader = 'x-trace-id' } = options;\n\n return function logixiaContextMiddleware(\n req: Record<string, unknown>,\n _res: unknown,\n next: () => void\n ): void {\n const headers = (req['headers'] ?? {}) as Record<string, string | undefined>;\n const traceId = sanitizeIncomingId(headers[traceIdHeader.toLowerCase()]) ?? randomShortId();\n const base: LogContext = { traceId };\n LogixiaContext.run({ ...base, ...(enrich ? enrich(req) : {}) }, next);\n };\n}\n\n/**\n * Create a Fastify lifecycle hook that wraps each request in a context scope.\n *\n * Register with `fastify.addHook('onRequest', createFastifyContextHook())`.\n */\nexport function createFastifyContextHook(\n options: {\n enrich?: (request: Record<string, unknown>) => Partial<LogContext>;\n traceIdHeader?: string;\n } = {}\n) {\n const { enrich, traceIdHeader = 'x-trace-id' } = options;\n\n return function logixiaFastifyHook(\n request: Record<string, unknown>,\n _reply: unknown,\n done: () => void\n ): void {\n const headers = (request['headers'] ?? {}) as Record<string, string | undefined>;\n const traceId =\n sanitizeIncomingId(headers[traceIdHeader.toLowerCase()]) ??\n sanitizeIncomingId(request['id']) ??\n randomShortId();\n const base: LogContext = { traceId };\n LogixiaContext.run({ ...base, ...(enrich ? enrich(request) : {}) }, done);\n };\n}\n"],"mappings":";;;;;;AAgCA,SAAS,gBAAwB;AAC/B,QAAO,YAAY,CAAC,MAAM,GAAG,EAAE;;AAajC,MAAM,WAAW,IAAI,mBAA+B;AAEpD,MAAa,iBAAiB;CAa5B,IAAO,OAAmB,UAAsB;EAC9C,MAAM,SAAS,SAAS,UAAU,IAAI,EAAE;AACxC,SAAO,SAAS,IAAI;GAAE,GAAG;GAAQ,GAAG;GAAO,EAAE,SAAS;;CAOxD,MAA8B;AAC5B,SAAO,SAAS,UAAU;;CAO5B,IAAI,QAAmC;EACrC,MAAM,QAAQ,SAAS,UAAU;AACjC,MAAI,CAAC,MAGH;AAEF,OAAK,MAAM,OAAO,OAAO,KAAK,OAAO,EAAE;AACrC,OAAI,QAAQ,eAAe,QAAQ,iBAAiB,QAAQ,YAAa;AACzE,SAAM,OAAO,OAAO;;;CAQxB,aAA4C;AAC1C,SAAO;;CAEV;;;;;;;;;;;AAYD,SAAgB,+BACd,UAKI,EAAE,EACN;CACA,MAAM,EAAE,QAAQ,gBAAgB,iBAAiB;AAEjD,QAAO,SAAS,yBACd,KACA,MACA,MACM;EAGN,MAAMA,OAAmB,EAAE,SADX,oBADC,IAAI,cAAc,EAAE,EACM,cAAc,aAAa,EAAE,IAAI,eAAe,EACvD;AACpC,iBAAe,IAAI;GAAE,GAAG;GAAM,GAAI,SAAS,OAAO,IAAI,GAAG,EAAE;GAAG,EAAE,KAAK;;;;;;;;AASzE,SAAgB,yBACd,UAGI,EAAE,EACN;CACA,MAAM,EAAE,QAAQ,gBAAgB,iBAAiB;AAEjD,QAAO,SAAS,mBACd,SACA,QACA,MACM;EAMN,MAAMA,OAAmB,EAAE,SAHzB,oBAFe,QAAQ,cAAc,EAAE,EAEZ,cAAc,aAAa,EAAE,IACxD,mBAAmB,QAAQ,MAAM,IACjC,eAAe,EACmB;AACpC,iBAAe,IAAI;GAAE,GAAG;GAAM,GAAI,SAAS,OAAO,QAAQ,GAAG,EAAE;GAAG,EAAE,KAAK"}
|
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
const require_chunk = require('./chunk-nOFOJqeH.js');
|
|
2
|
-
const require_trace_utils = require('./trace.utils-DpBOLDtq.js');
|
|
3
|
-
let node_crypto = require("node:crypto");
|
|
4
|
-
node_crypto = require_chunk.__toESM(node_crypto);
|
|
5
|
-
let node_async_hooks = require("node:async_hooks");
|
|
6
|
-
node_async_hooks = require_chunk.__toESM(node_async_hooks);
|
|
7
|
-
|
|
8
|
-
//#region src/context/async-context.ts
|
|
9
|
-
/** Generates an 8-character random ID using Node's crypto module. */
|
|
10
|
-
function randomShortId() {
|
|
11
|
-
return (0, node_crypto.randomUUID)().slice(0, 8);
|
|
12
|
-
}
|
|
13
|
-
const _storage = new node_async_hooks.AsyncLocalStorage();
|
|
14
|
-
const LogixiaContext = {
|
|
15
|
-
run(store, callback) {
|
|
16
|
-
const parent = _storage.getStore() ?? {};
|
|
17
|
-
return _storage.run({
|
|
18
|
-
...parent,
|
|
19
|
-
...store
|
|
20
|
-
}, callback);
|
|
21
|
-
},
|
|
22
|
-
get() {
|
|
23
|
-
return _storage.getStore();
|
|
24
|
-
},
|
|
25
|
-
set(fields) {
|
|
26
|
-
const store = _storage.getStore();
|
|
27
|
-
if (!store) return;
|
|
28
|
-
for (const key of Object.keys(fields)) {
|
|
29
|
-
if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
|
|
30
|
-
store[key] = fields[key];
|
|
31
|
-
}
|
|
32
|
-
},
|
|
33
|
-
getStorage() {
|
|
34
|
-
return _storage;
|
|
35
|
-
}
|
|
36
|
-
};
|
|
37
|
-
/**
|
|
38
|
-
* Create an Express/Connect-compatible middleware that wraps each request in
|
|
39
|
-
* a `LogixiaContext.run()` scope populated with common request fields.
|
|
40
|
-
*
|
|
41
|
-
* @example
|
|
42
|
-
* ```ts
|
|
43
|
-
* import { createExpressContextMiddleware } from 'logixia';
|
|
44
|
-
* app.use(createExpressContextMiddleware());
|
|
45
|
-
* ```
|
|
46
|
-
*/
|
|
47
|
-
function createExpressContextMiddleware(options = {}) {
|
|
48
|
-
const { enrich, traceIdHeader = "x-trace-id" } = options;
|
|
49
|
-
return function logixiaContextMiddleware(req, _res, next) {
|
|
50
|
-
const base = { traceId: require_trace_utils.sanitizeIncomingId((req["headers"] ?? {})[traceIdHeader.toLowerCase()]) ?? randomShortId() };
|
|
51
|
-
LogixiaContext.run({
|
|
52
|
-
...base,
|
|
53
|
-
...enrich ? enrich(req) : {}
|
|
54
|
-
}, next);
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Create a Fastify lifecycle hook that wraps each request in a context scope.
|
|
59
|
-
*
|
|
60
|
-
* Register with `fastify.addHook('onRequest', createFastifyContextHook())`.
|
|
61
|
-
*/
|
|
62
|
-
function createFastifyContextHook(options = {}) {
|
|
63
|
-
const { enrich, traceIdHeader = "x-trace-id" } = options;
|
|
64
|
-
return function logixiaFastifyHook(request, _reply, done) {
|
|
65
|
-
const base = { traceId: require_trace_utils.sanitizeIncomingId((request["headers"] ?? {})[traceIdHeader.toLowerCase()]) ?? require_trace_utils.sanitizeIncomingId(request["id"]) ?? randomShortId() };
|
|
66
|
-
LogixiaContext.run({
|
|
67
|
-
...base,
|
|
68
|
-
...enrich ? enrich(request) : {}
|
|
69
|
-
}, done);
|
|
70
|
-
};
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
//#endregion
|
|
74
|
-
Object.defineProperty(exports, 'LogixiaContext', {
|
|
75
|
-
enumerable: true,
|
|
76
|
-
get: function () {
|
|
77
|
-
return LogixiaContext;
|
|
78
|
-
}
|
|
79
|
-
});
|
|
80
|
-
Object.defineProperty(exports, 'createExpressContextMiddleware', {
|
|
81
|
-
enumerable: true,
|
|
82
|
-
get: function () {
|
|
83
|
-
return createExpressContextMiddleware;
|
|
84
|
-
}
|
|
85
|
-
});
|
|
86
|
-
Object.defineProperty(exports, 'createFastifyContextHook', {
|
|
87
|
-
enumerable: true,
|
|
88
|
-
get: function () {
|
|
89
|
-
return createFastifyContextHook;
|
|
90
|
-
}
|
|
91
|
-
});
|
|
92
|
-
//# sourceMappingURL=async-context-DyQQYq3I.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"async-context-DyQQYq3I.js","names":["AsyncLocalStorage","base: LogContext","sanitizeIncomingId"],"sources":["../src/context/async-context.ts"],"sourcesContent":["/**\n * LogixiaContext — Zero-boilerplate AsyncLocalStorage context propagation.\n *\n * Lets every `logger.info()` call inside a context automatically pick up stored\n * fields (requestId, userId, tenantId, …) without passing them through every function.\n *\n * Works across `Promise.all`, `setTimeout`, and event emitters — anything that\n * inherits the async execution context.\n *\n * @example\n * ```ts\n * import { LogixiaContext } from 'logixia';\n *\n * // Wrap a request handler:\n * app.use((req, res, next) => {\n * LogixiaContext.run({ requestId: req.id, userId: req.user?.id }, next);\n * });\n *\n * // Anywhere deeper in the call tree:\n * async function processOrder(orderId: string) {\n * const ctx = LogixiaContext.get(); // { requestId, userId, orderId }\n * logger.info('Processing order', { orderId, ...ctx });\n * }\n * ```\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { randomUUID } from 'node:crypto';\n\nimport { sanitizeIncomingId } from '../utils/trace.utils';\n\n/** Generates an 8-character random ID using Node's crypto module. */\nfunction randomShortId(): string {\n return randomUUID().slice(0, 8);\n}\n\nexport interface LogContext {\n traceId?: string;\n spanId?: string;\n userId?: string;\n tenantId?: string;\n sessionId?: string;\n [key: string]: unknown;\n}\n\n// Module-level singleton so all loggers share the same ALS store.\nconst _storage = new AsyncLocalStorage<LogContext>();\n\nexport const LogixiaContext = {\n /**\n * Run `callback` inside an async context that carries `store` fields.\n * All loggers queried within `callback` (and its async descendants) will\n * automatically see these fields.\n *\n * @example\n * ```ts\n * LogixiaContext.run({ requestId: 'abc', userId: '42' }, async () => {\n * await processOrder(); // sees requestId + userId in every log\n * });\n * ```\n */\n run<T>(store: LogContext, callback: () => T): T {\n const parent = _storage.getStore() ?? {};\n return _storage.run({ ...parent, ...store }, callback);\n },\n\n /**\n * Return the context fields active in the current async scope.\n * Returns `undefined` when called outside any `LogixiaContext.run()`.\n */\n get(): LogContext | undefined {\n return _storage.getStore();\n },\n\n /**\n * Merge `fields` into the **existing** context for the current scope.\n * If called outside a `run()` context this is a no-op (logs a dev warning).\n */\n set(fields: Partial<LogContext>): void {\n const store = _storage.getStore();\n if (!store) {\n // Silently ignore — avoids crashing in code that may call setContext\n // before a request context is established (e.g. background jobs).\n return;\n }\n for (const key of Object.keys(fields)) {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;\n store[key] = fields[key];\n }\n },\n\n /**\n * Retrieve the underlying `AsyncLocalStorage` instance.\n * Useful for advanced use-cases like custom middleware.\n */\n getStorage(): AsyncLocalStorage<LogContext> {\n return _storage;\n },\n};\n\n/**\n * Create an Express/Connect-compatible middleware that wraps each request in\n * a `LogixiaContext.run()` scope populated with common request fields.\n *\n * @example\n * ```ts\n * import { createExpressContextMiddleware } from 'logixia';\n * app.use(createExpressContextMiddleware());\n * ```\n */\nexport function createExpressContextMiddleware(\n options: {\n /** Extract additional fields from the request. */\n enrich?: (req: Record<string, unknown>) => Partial<LogContext>;\n /** Header to read the traceId from. Default: 'x-trace-id'. */\n traceIdHeader?: string;\n } = {}\n) {\n const { enrich, traceIdHeader = 'x-trace-id' } = options;\n\n return function logixiaContextMiddleware(\n req: Record<string, unknown>,\n _res: unknown,\n next: () => void\n ): void {\n const headers = (req['headers'] ?? {}) as Record<string, string | undefined>;\n const traceId = sanitizeIncomingId(headers[traceIdHeader.toLowerCase()]) ?? randomShortId();\n const base: LogContext = { traceId };\n LogixiaContext.run({ ...base, ...(enrich ? enrich(req) : {}) }, next);\n };\n}\n\n/**\n * Create a Fastify lifecycle hook that wraps each request in a context scope.\n *\n * Register with `fastify.addHook('onRequest', createFastifyContextHook())`.\n */\nexport function createFastifyContextHook(\n options: {\n enrich?: (request: Record<string, unknown>) => Partial<LogContext>;\n traceIdHeader?: string;\n } = {}\n) {\n const { enrich, traceIdHeader = 'x-trace-id' } = options;\n\n return function logixiaFastifyHook(\n request: Record<string, unknown>,\n _reply: unknown,\n done: () => void\n ): void {\n const headers = (request['headers'] ?? {}) as Record<string, string | undefined>;\n const traceId =\n sanitizeIncomingId(headers[traceIdHeader.toLowerCase()]) ??\n sanitizeIncomingId(request['id']) ??\n randomShortId();\n const base: LogContext = { traceId };\n LogixiaContext.run({ ...base, ...(enrich ? enrich(request) : {}) }, done);\n };\n}\n"],"mappings":";;;;;;;;;AAgCA,SAAS,gBAAwB;AAC/B,qCAAmB,CAAC,MAAM,GAAG,EAAE;;AAajC,MAAM,WAAW,IAAIA,oCAA+B;AAEpD,MAAa,iBAAiB;CAa5B,IAAO,OAAmB,UAAsB;EAC9C,MAAM,SAAS,SAAS,UAAU,IAAI,EAAE;AACxC,SAAO,SAAS,IAAI;GAAE,GAAG;GAAQ,GAAG;GAAO,EAAE,SAAS;;CAOxD,MAA8B;AAC5B,SAAO,SAAS,UAAU;;CAO5B,IAAI,QAAmC;EACrC,MAAM,QAAQ,SAAS,UAAU;AACjC,MAAI,CAAC,MAGH;AAEF,OAAK,MAAM,OAAO,OAAO,KAAK,OAAO,EAAE;AACrC,OAAI,QAAQ,eAAe,QAAQ,iBAAiB,QAAQ,YAAa;AACzE,SAAM,OAAO,OAAO;;;CAQxB,aAA4C;AAC1C,SAAO;;CAEV;;;;;;;;;;;AAYD,SAAgB,+BACd,UAKI,EAAE,EACN;CACA,MAAM,EAAE,QAAQ,gBAAgB,iBAAiB;AAEjD,QAAO,SAAS,yBACd,KACA,MACA,MACM;EAGN,MAAMC,OAAmB,EAAE,SADXC,wCADC,IAAI,cAAc,EAAE,EACM,cAAc,aAAa,EAAE,IAAI,eAAe,EACvD;AACpC,iBAAe,IAAI;GAAE,GAAG;GAAM,GAAI,SAAS,OAAO,IAAI,GAAG,EAAE;GAAG,EAAE,KAAK;;;;;;;;AASzE,SAAgB,yBACd,UAGI,EAAE,EACN;CACA,MAAM,EAAE,QAAQ,gBAAgB,iBAAiB;AAEjD,QAAO,SAAS,mBACd,SACA,QACA,MACM;EAMN,MAAMD,OAAmB,EAAE,SAHzBC,wCAFe,QAAQ,cAAc,EAAE,EAEZ,cAAc,aAAa,EAAE,IACxDA,uCAAmB,QAAQ,MAAM,IACjC,eAAe,EACmB;AACpC,iBAAe,IAAI;GAAE,GAAG;GAAM,GAAI,SAAS,OAAO,QAAQ,GAAG,EAAE;GAAG,EAAE,KAAK"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"azure-monitor.transport-CHnjVRF-.mjs","names":["SEVERITY_MAP: Record<string, number>","reqUrl: URL"],"sources":["../src/transports/azure-monitor.transport.ts"],"sourcesContent":["/**\n * logixia — Azure Monitor / Application Insights transport\n *\n * Sends log entries to Azure Monitor via the Data Collection Rules (DCR) API\n * using the Logs Ingestion API (the modern replacement for the legacy HTTP\n * Data Collector API).\n *\n * Maps logixia levels to Application Insights severity levels:\n * verbose → 0, debug → 1, info → 1, warn → 2, error → 3, critical → 4\n *\n * @example\n * ```ts\n * import { AzureMonitorTransport } from 'logixia';\n *\n * const logger = createLogger({\n * transports: {\n * azure: new AzureMonitorTransport({\n * // Logs Ingestion API endpoint (from your DCR)\n * endpoint: 'https://<dce>.ingest.monitor.azure.com',\n * ruleId: 'dcr-xxxxxxxxxxxxxxxx',\n * streamName: 'Custom-LogixiaLogs',\n * // Client credentials (or managed identity via no-credential mode)\n * tenantId: process.env.AZURE_TENANT_ID,\n * clientId: process.env.AZURE_CLIENT_ID,\n * clientSecret: process.env.AZURE_CLIENT_SECRET,\n * }),\n * },\n * });\n * ```\n */\n\nimport type { IAsyncTransport, TransportLogEntry } from '../types/transport.types';\nimport { internalError, internalWarn } from '../utils/internal-log';\nimport { stringifyForLog } from '../utils/safe-stringify';\nimport {\n BatchBuffer,\n DEFAULT_MAX_BUFFER_SIZE,\n DEFAULT_REQUEST_TIMEOUT_MS,\n httpRequest,\n} from './batch-buffer';\n\n/**\n * Azure AD tenant IDs are either a GUID or a verified domain (e.g. `contoso.onmicrosoft.com`).\n * This pattern is deliberately permissive on structure but strict on character\n * set — it rejects the breakout characters (`/`, `@`, `:`, `?`, `#`, whitespace)\n * that would let a hostile config smuggle a different host, path, or query into\n * the OAuth token URL.\n */\nconst AZURE_TENANT_RE = /^[a-z0-9][a-z0-9.-]{1,253}$/i;\n\nexport interface AzureMonitorTransportConfig {\n /** DCE (Data Collection Endpoint) URL, e.g. `https://<name>.ingest.monitor.azure.com`. */\n endpoint: string;\n /** Data Collection Rule immutable ID (from Azure portal). */\n ruleId: string;\n /** Stream name defined in the DCR, e.g. `'Custom-LogixiaLogs_CL'`. */\n streamName: string;\n /** Azure AD tenant ID for OAuth2 client-credentials flow. */\n tenantId?: string;\n /** Azure AD app (service principal) client ID. */\n clientId?: string;\n /** Azure AD app client secret. */\n clientSecret?: string;\n /** Number of entries to batch. @default 200 */\n batchSize?: number;\n /** Flush interval in ms. @default 5000 */\n flushIntervalMs?: number;\n /** Abort a request that has not finished after this many ms. @default 10000 */\n requestTimeoutMs?: number;\n /** Max buffered entries; the oldest are dropped past this. @default 10000 */\n maxBufferSize?: number;\n level?: string;\n}\n\nconst SEVERITY_MAP: Record<string, number> = {\n verbose: 0,\n trace: 0,\n debug: 1,\n info: 1,\n log: 1,\n warn: 2,\n warning: 2,\n error: 3,\n critical: 4,\n fatal: 4,\n};\n\n/**\n * Azure Monitor Logs Ingestion transport.\n */\nexport class AzureMonitorTransport implements IAsyncTransport {\n public readonly name = 'azure-monitor';\n public readonly batchSize: number;\n public readonly flushInterval: number;\n public readonly level: string | undefined;\n\n private readonly buffer: BatchBuffer<TransportLogEntry>;\n private readonly requestTimeoutMs: number;\n private flushTimer: NodeJS.Timeout | null = null;\n private accessToken: string | null = null;\n private tokenExpiry = 0;\n\n private readonly endpoint: string;\n private readonly ruleId: string;\n private readonly streamName: string;\n private readonly tenantId: string | undefined;\n private readonly clientId: string | undefined;\n private readonly clientSecret: string | undefined;\n\n constructor(config: AzureMonitorTransportConfig) {\n this.endpoint = config.endpoint.replace(/\\/$/, '');\n this.ruleId = config.ruleId;\n this.streamName = config.streamName;\n this.tenantId = config.tenantId ?? process.env['AZURE_TENANT_ID'];\n this.clientId = config.clientId ?? process.env['AZURE_CLIENT_ID'];\n this.clientSecret = config.clientSecret ?? process.env['AZURE_CLIENT_SECRET'];\n this.batchSize = config.batchSize ?? 200;\n this.flushInterval = config.flushIntervalMs ?? 5000;\n this.level = config.level;\n this.requestTimeoutMs = config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n this.buffer = new BatchBuffer<TransportLogEntry>({\n name: 'AzureMonitorTransport',\n batchSize: this.batchSize,\n maxBufferSize: config.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE,\n send: (entries) => this.sendEntries(entries),\n });\n\n this.flushTimer = setInterval(() => {\n this.flush().catch(() => {});\n }, this.flushInterval);\n if (this.flushTimer.unref) this.flushTimer.unref();\n }\n\n write(entry: TransportLogEntry): void {\n this.buffer.push(entry);\n this.buffer.flushIfFull();\n }\n\n flush(): Promise<void> {\n return this.buffer.flush();\n }\n\n /**\n * Flush remaining entries and stop the interval timer on shutdown. Without\n * this the manager's close() skipped the transport (close was undefined) and\n * buffered entries were lost on deploy. Waits for any in-flight send first.\n */\n async close(): Promise<void> {\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n await this.buffer.close();\n }\n\n private toAzureRecord(entry: TransportLogEntry): Record<string, unknown> {\n return {\n TimeGenerated: entry.timestamp ?? new Date().toISOString(),\n SeverityLevel: SEVERITY_MAP[entry.level.toLowerCase()] ?? 1,\n Message: entry.message,\n AppName: entry.appName,\n Context: entry.context ?? '',\n TraceId: entry.traceId ?? '',\n Properties: stringifyForLog(entry.data ?? {}),\n };\n }\n\n private async getAccessToken(): Promise<string | null> {\n if (this.accessToken && Date.now() < this.tokenExpiry) return this.accessToken;\n\n if (!this.tenantId || !this.clientId || !this.clientSecret) {\n internalWarn(\n 'AzureMonitorTransport: missing credentials — set tenantId, clientId, clientSecret'\n );\n return null;\n }\n\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: this.clientId,\n client_secret: this.clientSecret,\n scope: 'https://monitor.azure.com/.default',\n }).toString();\n\n const tenantId = this.tenantId;\n if (!AZURE_TENANT_RE.test(tenantId)) {\n internalWarn(\n `AzureMonitorTransport: refusing to request token — tenantId \"${tenantId}\" is not a valid GUID or domain`\n );\n return null;\n }\n\n const reqUrl = new URL(\n `https://login.microsoftonline.com/${encodeURIComponent(tenantId)}/oauth2/v2.0/token`\n );\n try {\n const res = await httpRequest({\n url: reqUrl,\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body,\n timeoutMs: this.requestTimeoutMs,\n label: 'Azure token request',\n });\n const parsed = JSON.parse(res.body) as { access_token?: string; expires_in?: number };\n if (!parsed.access_token) return null;\n this.accessToken = parsed.access_token;\n this.tokenExpiry = Date.now() + (parsed.expires_in ?? 3600) * 1000 - 60_000;\n return this.accessToken;\n } catch (err) {\n internalError('AzureMonitorTransport token request failed', err);\n return null;\n }\n }\n\n private async sendEntries(entries: TransportLogEntry[]): Promise<void> {\n const token = await this.getAccessToken();\n if (!token) throw new Error('AzureMonitorTransport: no access token available');\n\n const records = entries.map((e) => this.toAzureRecord(e));\n const body = stringifyForLog(records);\n let reqUrl: URL;\n try {\n // Build from the user-configured DCE endpoint; encodeURIComponent-ing the\n // ruleId/streamName stops a hostile config from smuggling extra path\n // segments or query params into the request.\n reqUrl = new URL(\n `dataCollectionRules/${encodeURIComponent(this.ruleId)}/streams/${encodeURIComponent(this.streamName)}?api-version=2023-01-01`,\n this.endpoint.endsWith('/') ? this.endpoint : `${this.endpoint}/`\n );\n } catch (error) {\n internalError(`AzureMonitorTransport: invalid endpoint \"${this.endpoint}\"`, error);\n return;\n }\n if (reqUrl.protocol !== 'https:') {\n internalError(`AzureMonitorTransport: endpoint must use https (got ${reqUrl.protocol})`);\n return;\n }\n\n await httpRequest({\n url: reqUrl,\n headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },\n body,\n timeoutMs: this.requestTimeoutMs,\n label: 'Azure Monitor API',\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AAgDA,MAAM,kBAAkB;AA0BxB,MAAMA,eAAuC;CAC3C,SAAS;CACT,OAAO;CACP,OAAO;CACP,MAAM;CACN,KAAK;CACL,MAAM;CACN,SAAS;CACT,OAAO;CACP,UAAU;CACV,OAAO;CACR;;;;AAKD,IAAa,wBAAb,MAA8D;CAmB5D,YAAY,QAAqC;cAlB1B;oBAOqB;qBACP;qBACf;AAUpB,OAAK,WAAW,OAAO,SAAS,QAAQ,OAAO,GAAG;AAClD,OAAK,SAAS,OAAO;AACrB,OAAK,aAAa,OAAO;AACzB,OAAK,WAAW,OAAO,YAAY,QAAQ,IAAI;AAC/C,OAAK,WAAW,OAAO,Y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AAO;GACR,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"azure-monitor.transport-Cn_3Usvu.d.ts","names":[],"sources":["../src/transports/azure-monitor.transport.ts"],"sourcesContent":[],"mappings":";;;;UAkDiB,2BAAA;;;;;;;;;;;;;;;;;;;;;;;;;;cAwCJ,qBAAA,YAAiC;;;;;;;;;;;;;;;;sBAmBxB;eAwBP;WAKJ;;;;;;WASM"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"azure-monitor.transport-CrvfHd9C.js","names":["SEVERITY_MAP: Record<string, number>","DEFAULT_REQUEST_TIMEOUT_MS","BatchBuffer","DEFAULT_MAX_BUFFER_SIZE","stringifyForLog","httpRequest","reqUrl: URL"],"sources":["../src/transports/azure-monitor.transport.ts"],"sourcesContent":["/**\n * logixia — Azure Monitor / Application Insights transport\n *\n * Sends log entries to Azure Monitor via the Data Collection Rules (DCR) API\n * using the Logs Ingestion API (the modern replacement for the legacy HTTP\n * Data Collector API).\n *\n * Maps logixia levels to Application Insights severity levels:\n * verbose → 0, debug → 1, info → 1, warn → 2, error → 3, critical → 4\n *\n * @example\n * ```ts\n * import { AzureMonitorTransport } from 'logixia';\n *\n * const logger = createLogger({\n * transports: {\n * azure: new AzureMonitorTransport({\n * // Logs Ingestion API endpoint (from your DCR)\n * endpoint: 'https://<dce>.ingest.monitor.azure.com',\n * ruleId: 'dcr-xxxxxxxxxxxxxxxx',\n * streamName: 'Custom-LogixiaLogs',\n * // Client credentials (or managed identity via no-credential mode)\n * tenantId: process.env.AZURE_TENANT_ID,\n * clientId: process.env.AZURE_CLIENT_ID,\n * clientSecret: process.env.AZURE_CLIENT_SECRET,\n * }),\n * },\n * });\n * ```\n */\n\nimport type { IAsyncTransport, TransportLogEntry } from '../types/transport.types';\nimport { internalError, internalWarn } from '../utils/internal-log';\nimport { stringifyForLog } from '../utils/safe-stringify';\nimport {\n BatchBuffer,\n DEFAULT_MAX_BUFFER_SIZE,\n DEFAULT_REQUEST_TIMEOUT_MS,\n httpRequest,\n} from './batch-buffer';\n\n/**\n * Azure AD tenant IDs are either a GUID or a verified domain (e.g. `contoso.onmicrosoft.com`).\n * This pattern is deliberately permissive on structure but strict on character\n * set — it rejects the breakout characters (`/`, `@`, `:`, `?`, `#`, whitespace)\n * that would let a hostile config smuggle a different host, path, or query into\n * the OAuth token URL.\n */\nconst AZURE_TENANT_RE = /^[a-z0-9][a-z0-9.-]{1,253}$/i;\n\nexport interface AzureMonitorTransportConfig {\n /** DCE (Data Collection Endpoint) URL, e.g. `https://<name>.ingest.monitor.azure.com`. */\n endpoint: string;\n /** Data Collection Rule immutable ID (from Azure portal). */\n ruleId: string;\n /** Stream name defined in the DCR, e.g. `'Custom-LogixiaLogs_CL'`. */\n streamName: string;\n /** Azure AD tenant ID for OAuth2 client-credentials flow. */\n tenantId?: string;\n /** Azure AD app (service principal) client ID. */\n clientId?: string;\n /** Azure AD app client secret. */\n clientSecret?: string;\n /** Number of entries to batch. @default 200 */\n batchSize?: number;\n /** Flush interval in ms. @default 5000 */\n flushIntervalMs?: number;\n /** Abort a request that has not finished after this many ms. @default 10000 */\n requestTimeoutMs?: number;\n /** Max buffered entries; the oldest are dropped past this. @default 10000 */\n maxBufferSize?: number;\n level?: string;\n}\n\nconst SEVERITY_MAP: Record<string, number> = {\n verbose: 0,\n trace: 0,\n debug: 1,\n info: 1,\n log: 1,\n warn: 2,\n warning: 2,\n error: 3,\n critical: 4,\n fatal: 4,\n};\n\n/**\n * Azure Monitor Logs Ingestion transport.\n */\nexport class AzureMonitorTransport implements IAsyncTransport {\n public readonly name = 'azure-monitor';\n public readonly batchSize: number;\n public readonly flushInterval: number;\n public readonly level: string | undefined;\n\n private readonly buffer: BatchBuffer<TransportLogEntry>;\n private readonly requestTimeoutMs: number;\n private flushTimer: NodeJS.Timeout | null = null;\n private accessToken: string | null = null;\n private tokenExpiry = 0;\n\n private readonly endpoint: string;\n private readonly ruleId: string;\n private readonly streamName: string;\n private readonly tenantId: string | undefined;\n private readonly clientId: string | undefined;\n private readonly clientSecret: string | undefined;\n\n constructor(config: AzureMonitorTransportConfig) {\n this.endpoint = config.endpoint.replace(/\\/$/, '');\n this.ruleId = config.ruleId;\n this.streamName = config.streamName;\n this.tenantId = config.tenantId ?? process.env['AZURE_TENANT_ID'];\n this.clientId = config.clientId ?? process.env['AZURE_CLIENT_ID'];\n this.clientSecret = config.clientSecret ?? process.env['AZURE_CLIENT_SECRET'];\n this.batchSize = config.batchSize ?? 200;\n this.flushInterval = config.flushIntervalMs ?? 5000;\n this.level = config.level;\n this.requestTimeoutMs = config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n this.buffer = new BatchBuffer<TransportLogEntry>({\n name: 'AzureMonitorTransport',\n batchSize: this.batchSize,\n maxBufferSize: config.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE,\n send: (entries) => this.sendEntries(entries),\n });\n\n this.flushTimer = setInterval(() => {\n this.flush().catch(() => {});\n }, this.flushInterval);\n if (this.flushTimer.unref) this.flushTimer.unref();\n }\n\n write(entry: TransportLogEntry): void {\n this.buffer.push(entry);\n this.buffer.flushIfFull();\n }\n\n flush(): Promise<void> {\n return this.buffer.flush();\n }\n\n /**\n * Flush remaining entries and stop the interval timer on shutdown. Without\n * this the manager's close() skipped the transport (close was undefined) and\n * buffered entries were lost on deploy. Waits for any in-flight send first.\n */\n async close(): Promise<void> {\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n await this.buffer.close();\n }\n\n private toAzureRecord(entry: TransportLogEntry): Record<string, unknown> {\n return {\n TimeGenerated: entry.timestamp ?? new Date().toISOString(),\n SeverityLevel: SEVERITY_MAP[entry.level.toLowerCase()] ?? 1,\n Message: entry.message,\n AppName: entry.appName,\n Context: entry.context ?? '',\n TraceId: entry.traceId ?? '',\n Properties: stringifyForLog(entry.data ?? {}),\n };\n }\n\n private async getAccessToken(): Promise<string | null> {\n if (this.accessToken && Date.now() < this.tokenExpiry) return this.accessToken;\n\n if (!this.tenantId || !this.clientId || !this.clientSecret) {\n internalWarn(\n 'AzureMonitorTransport: missing credentials — set tenantId, clientId, clientSecret'\n );\n return null;\n }\n\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: this.clientId,\n client_secret: this.clientSecret,\n scope: 'https://monitor.azure.com/.default',\n }).toString();\n\n const tenantId = this.tenantId;\n if (!AZURE_TENANT_RE.test(tenantId)) {\n internalWarn(\n `AzureMonitorTransport: refusing to request token — tenantId \"${tenantId}\" is not a valid GUID or domain`\n );\n return null;\n }\n\n const reqUrl = new URL(\n `https://login.microsoftonline.com/${encodeURIComponent(tenantId)}/oauth2/v2.0/token`\n );\n try {\n const res = await httpRequest({\n url: reqUrl,\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body,\n timeoutMs: this.requestTimeoutMs,\n label: 'Azure token request',\n });\n const parsed = JSON.parse(res.body) as { access_token?: string; expires_in?: number };\n if (!parsed.access_token) return null;\n this.accessToken = parsed.access_token;\n this.tokenExpiry = Date.now() + (parsed.expires_in ?? 3600) * 1000 - 60_000;\n return this.accessToken;\n } catch (err) {\n internalError('AzureMonitorTransport token request failed', err);\n return null;\n }\n }\n\n private async sendEntries(entries: TransportLogEntry[]): Promise<void> {\n const token = await this.getAccessToken();\n if (!token) throw new Error('AzureMonitorTransport: no access token available');\n\n const records = entries.map((e) => this.toAzureRecord(e));\n const body = stringifyForLog(records);\n let reqUrl: URL;\n try {\n // Build from the user-configured DCE endpoint; encodeURIComponent-ing the\n // ruleId/streamName stops a hostile config from smuggling extra path\n // segments or query params into the request.\n reqUrl = new URL(\n `dataCollectionRules/${encodeURIComponent(this.ruleId)}/streams/${encodeURIComponent(this.streamName)}?api-version=2023-01-01`,\n this.endpoint.endsWith('/') ? this.endpoint : `${this.endpoint}/`\n );\n } catch (error) {\n internalError(`AzureMonitorTransport: invalid endpoint \"${this.endpoint}\"`, error);\n return;\n }\n if (reqUrl.protocol !== 'https:') {\n internalError(`AzureMonitorTransport: endpoint must use https (got ${reqUrl.protocol})`);\n return;\n }\n\n await httpRequest({\n url: reqUrl,\n headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },\n body,\n timeoutMs: this.requestTimeoutMs,\n label: 'Azure Monitor API',\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AAgDA,MAAM,kBAAkB;AA0BxB,MAAMA,eAAuC;CAC3C,SAAS;CACT,OAAO;CACP,OAAO;CACP,MAAM;CACN,KAAK;CACL,MAAM;CACN,SAAS;CACT,OAAO;CACP,UAAU;CACV,OAAO;CACR;;;;AAKD,IAAa,wBAAb,MAA8D;CAmB5D,YAAY,QAAqC;cAlB1B;oBAOqB;qBACP;qBACf;AAUpB,OAAK,WAAW,OAAO,SAAS,QAAQ,OAAO,GAAG;AAClD,OAAK,SAAS,OAAO;AACrB,OAAK,aAAa,OAAO;AACzB,OAAK,WAAW,OAAO,YAAY,QAAQ,IAAI;AAC/C,OAAK,WAAW,OAAO,YAAY,QAAQ,IAAI;AAC/C,OAAK,eAAe,OAAO,gBAAgB,QAAQ,IAAI;AACvD,OAAK,YAAY,OAAO,aAAa;AACrC,OAAK,gBAAgB,OAAO,mBAAmB;AAC/C,OAAK,QAAQ,OAAO;AACpB,OAAK,mBAAmB,OAAO,oBAAoBC;AACnD,OAAK,SAAS,IAAIC,iCAA+B;GAC/C,MAAM;GACN,WAAW,KAAK;GAChB,eAAe,OAAO,iBAAiBC;GACvC,OAAO,YAAY,KAAK,YAAY,QAAQ;GAC7C,CAAC;AAEF,OAAK,aAAa,kBAAkB;AAClC,QAAK,OAAO,CAAC,YAAY,GAAG;KAC3B,KAAK,cAAc;AACtB,MAAI,KAAK,WAAW,MAAO,MAAK,WAAW,OAAO;;CAGpD,MAAM,OAAgC;AACpC,OAAK,OAAO,KAAK,MAAM;AACvB,OAAK,OAAO,aAAa;;CAG3B,QAAuB;AACrB,SAAO,KAAK,OAAO,OAAO;;;;;;;CAQ5B,MAA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AO;;;CAIX,MAAc,YAAY,SAA6C;EACrE,MAAM,QAAQ,MAAM,KAAK,gBAAgB;AACzC,MAAI,CAAC,MAAO,OAAM,IAAI,MAAM,mDAAmD;EAG/E,MAAM,OAAOD,uCADG,QAAQ,KAAK,MAAM,KAAK,cAAc,EAAE,CAAC,CACpB;EACrC,IAAIE;AACJ,MAAI;AAIF,YAAS,IAAI,IACX,uBAAuB,mBAAmB,KAAK,OAAO,CAAC,WAAW,mBAAmB,KAAK,WAAW,CAAC,0BACtG,KAAK,SAAS,SAAS,IAAI,GAAG,KAAK,WAAW,GAAG,KAAK,SAAS,GAChE;WACM,OAAO;AACd,sCAAc,4CAA4C,KAAK,SAAS,IAAI,MAAM;AAClF;;AAEF,MAAI,OAAO,aAAa,UAAU;AAChC,sCAAc,uDAAuD,OAAO,SAAS,GAAG;AACxF;;AAGF,QAAMD,iCAAY;GAChB,KAAK;GACL,SAAS;IAAE,eAAe,UAAU;IAAS,gBAAgB;IAAoB;GACjF;GACA,WAAW,KAAK;GAChB,OAAO;GACR,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"azure-monitor.transport-D7Da4RAb.d.mts","names":[],"sources":["../src/transports/azure-monitor.transport.ts"],"sourcesContent":[],"mappings":";;;;UAkDiB,2BAAA;;;;;;;;;;;;;;;;;;;;;;;;;;cAwCJ,qBAAA,YAAiC;;;;;;;;;;;;;;;;sBAmBxB;eAwBP;WAKJ;;;;;;WASM"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"batch-buffer-BY-mRWIK.js","names":["status: number","body: string","http","https","opts: BatchBufferOptions<T>"],"sources":["../src/transports/batch-buffer.ts"],"sourcesContent":["/**\n * Shared batching core for the network transports (OTLP, CloudWatch, GCP, Azure).\n *\n * - one send in flight at a time; flush() and close() join it instead of\n * racing it, so close() cannot return while a request is still on the wire\n * - a failed batch goes back to the front in its original order\n * - 4xx responses other than 429 drop the batch with a warning instead of\n * retrying a request the server will never accept\n * - the buffer is capped; when full the oldest entries are dropped\n */\n\nimport * as http from 'node:http';\nimport * as https from 'node:https';\n\nimport { internalError, internalWarn } from '../utils/internal-log';\n\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;\nexport const DEFAULT_MAX_BUFFER_SIZE = 10_000;\nconst WARN_INTERVAL_MS = 10_000;\nconst MAX_ERROR_BODY = 500;\nconst MAX_BACKOFF_MS = 30_000;\n\nexport class HttpError extends Error {\n constructor(\n public readonly status: number,\n public readonly body: string,\n label: string\n ) {\n const detail = body ? `: ${body.slice(0, MAX_ERROR_BODY)}` : '';\n super(`${label} returned HTTP ${status}${detail}`);\n this.name = 'HttpError';\n }\n}\n\nexport function isPermanentHttpError(err: unknown): boolean {\n return err instanceof HttpError && err.status >= 400 && err.status < 500 && err.status !== 429;\n}\n\nexport interface HttpRequestOptions {\n url: URL;\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n timeoutMs: number;\n label: string;\n}\n\nexport interface HttpResult {\n status: number;\n body: string;\n}\n\n/** One request with a hard timeout. Rejects with HttpError on any non-2xx status. */\nexport function httpRequest(opts: HttpRequestOptions): Promise<HttpResult> {\n const { url, method = 'POST', headers = {}, body, timeoutMs, label } = opts;\n const transport = url.protocol === 'http:' ? http : https;\n return new Promise<HttpResult>((resolve, reject) => {\n const req = transport.request(\n {\n protocol: url.protocol,\n hostname: url.hostname,\n port: url.port || undefined,\n path: `${url.pathname}${url.search}`,\n method,\n headers:\n body === undefined ? headers : { ...headers, 'Content-Length': Buffer.byteLength(body) },\n },\n (res) => {\n let raw = '';\n res.on('data', (c: Buffer) => (raw += c.toString()));\n res.on('end', () => {\n const status = res.statusCode ?? 0;\n if (status >= 200 && status < 300) resolve({ status, body: raw });\n else reject(new HttpError(status, raw, label));\n });\n res.on('error', reject);\n }\n );\n req.setTimeout(timeoutMs, () => {\n req.destroy(new Error(`${label} timed out after ${timeoutMs}ms`));\n });\n req.on('error', reject);\n if (body !== undefined) req.write(body);\n req.end();\n });\n}\n\nexport interface BatchBufferOptions<T> {\n name: string;\n batchSize: number;\n maxBufferSize?: number;\n send: (items: T[]) => Promise<void>;\n /** Overrides the default drop-on-4xx rule. Return true to keep and retry the batch. */\n shouldRetry?: (err: unknown) => boolean;\n}\n\nexport class BatchBuffer<T> {\n private items: T[] = [];\n private inFlight: Promise<void> | undefined;\n private dropped = 0;\n private lastDropWarn = 0;\n private failures = 0;\n private retryAfter = 0;\n\n constructor(private readonly opts: BatchBufferOptions<T>) {}\n\n get length(): number {\n return this.items.length;\n }\n\n get batchSize(): number {\n return this.opts.batchSize;\n }\n\n push(item: T): void {\n this.items.push(item);\n this.enforceCap();\n }\n\n /** Threshold flush for write(): skipped while a send is running or the endpoint is backing off. */\n flushIfFull(): void {\n if (this.items.length < this.opts.batchSize || this.inFlight || Date.now() < this.retryAfter) {\n return;\n }\n this.flush().catch(() => {});\n }\n\n flush(): Promise<void> {\n if (!this.inFlight) {\n this.inFlight = this.drain().finally(() => {\n this.inFlight = undefined;\n });\n }\n return this.inFlight;\n }\n\n /** Flush up to `attempts` times, then report whatever is still undelivered. */\n async close(attempts = 3): Promise<void> {\n await this.inFlight;\n for (let i = 0; i < attempts && this.items.length > 0; i += 1) {\n await this.flush();\n }\n if (this.items.length > 0) {\n internalError(\n `${this.opts.name} closing with ${this.items.length} undelivered entr${this.items.length === 1 ? 'y' : 'ies'}`\n );\n }\n }\n\n private async drain(): Promise<void> {\n while (this.items.length > 0) {\n const batch = this.items.splice(0, this.opts.batchSize);\n try {\n await this.opts.send(batch);\n this.failures = 0;\n } catch (err) {\n const retry = this.opts.shouldRetry\n ? this.opts.shouldRetry(err)\n : !isPermanentHttpError(err);\n if (!retry) {\n internalWarn(\n `${this.opts.name}: dropping ${batch.length} entr${batch.length === 1 ? 'y' : 'ies'} the server rejected (${err instanceof Error ? err.message : String(err)})`\n );\n continue;\n }\n internalError(`${this.opts.name} flush error`, err);\n this.items.unshift(...batch);\n this.enforceCap();\n this.failures += 1;\n this.retryAfter = Date.now() + Math.min(MAX_BACKOFF_MS, 1000 * 2 ** (this.failures - 1));\n return;\n }\n }\n }\n\n private enforceCap(): void {\n const max = this.opts.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE;\n const excess = this.items.length - max;\n if (excess <= 0) return;\n this.items.splice(0, excess);\n this.dropped += excess;\n const now = Date.now();\n if (now - this.lastDropWarn >= WARN_INTERVAL_MS) {\n internalWarn(\n `${this.opts.name}: buffer full (${max}), dropped ${this.dropped} oldest entr${this.dropped === 1 ? 'y' : 'ies'}`\n );\n this.dropped = 0;\n this.lastDropWarn = now;\n }\n }\n}\n"],"mappings":";;;;;;;;AAgBA,MAAa,6BAA6B;AAC1C,MAAa,0BAA0B;AACvC,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AAEvB,IAAa,YAAb,cAA+B,MAAM;CACnC,YACE,AAAgBA,QAChB,AAAgBC,MAChB,OACA;EACA,MAAM,SAAS,OAAO,KAAK,KAAK,MAAM,GAAG,eAAe,KAAK;AAC7D,QAAM,GAAG,MAAM,iBAAiB,SAAS,SAAS;EALlC;EACA;AAKhB,OAAK,OAAO;;;AAIhB,SAAgB,qBAAqB,KAAuB;AAC1D,QAAO,eAAe,aAAa,IAAI,UAAU,OAAO,IAAI,SAAS,OAAO,IAAI,WAAW;;;AAkB7F,SAAgB,YAAY,MAA+C;CACzE,MAAM,EAAE,KAAK,SAAS,QAAQ,UAAU,EAAE,EAAE,MAAM,WAAW,UAAU;CACvE,MAAM,YAAY,IAAI,aAAa,UAAUC,YAAOC;AACpD,QAAO,IAAI,SAAqB,SAAS,WAAW;EAClD,MAAM,MAAM,UAAU,QACpB;GACE,UAAU,IAAI;GACd,UAAU,IAAI;GACd,MAAM,IAAI,QAAQ;GAClB,MAAM,GAAG,IAAI,WAAW,IAAI;GAC5B;GACA,SACE,SAAS,SAAY,UAAU;IAAE,GAAG;IAAS,kBAAkB,OAAO,WAAW,KAAK;IAAE;GAC3F,GACA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