matterbridge 3.4.3-dev-20251209-e6cb85f → 3.4.3
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 +2 -3
- package/dist/broadcastServer.d.ts +144 -0
- package/dist/broadcastServer.d.ts.map +1 -0
- package/dist/broadcastServer.js +119 -0
- package/dist/broadcastServer.js.map +1 -0
- package/dist/broadcastServerTypes.d.ts +841 -0
- package/dist/broadcastServerTypes.d.ts.map +1 -0
- package/dist/broadcastServerTypes.js +24 -0
- package/dist/broadcastServerTypes.js.map +1 -0
- package/dist/cli.d.ts +30 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +97 -1
- package/dist/cli.js.map +1 -0
- package/dist/cliEmitter.d.ts +50 -0
- package/dist/cliEmitter.d.ts.map +1 -0
- package/dist/cliEmitter.js +37 -0
- package/dist/cliEmitter.js.map +1 -0
- package/dist/cliHistory.d.ts +48 -0
- package/dist/cliHistory.d.ts.map +1 -0
- package/dist/cliHistory.js +38 -0
- package/dist/cliHistory.js.map +1 -0
- package/dist/clusters/export.d.ts +2 -0
- package/dist/clusters/export.d.ts.map +1 -0
- package/dist/clusters/export.js +2 -0
- package/dist/clusters/export.js.map +1 -0
- package/dist/deviceManager.d.ts +135 -0
- package/dist/deviceManager.d.ts.map +1 -0
- package/dist/deviceManager.js +113 -1
- package/dist/deviceManager.js.map +1 -0
- package/dist/devices/airConditioner.d.ts +98 -0
- package/dist/devices/airConditioner.d.ts.map +1 -0
- package/dist/devices/airConditioner.js +57 -0
- package/dist/devices/airConditioner.js.map +1 -0
- package/dist/devices/batteryStorage.d.ts +48 -0
- package/dist/devices/batteryStorage.d.ts.map +1 -0
- package/dist/devices/batteryStorage.js +48 -1
- package/dist/devices/batteryStorage.js.map +1 -0
- package/dist/devices/cooktop.d.ts +61 -0
- package/dist/devices/cooktop.d.ts.map +1 -0
- package/dist/devices/cooktop.js +56 -0
- package/dist/devices/cooktop.js.map +1 -0
- package/dist/devices/dishwasher.d.ts +71 -0
- package/dist/devices/dishwasher.d.ts.map +1 -0
- package/dist/devices/dishwasher.js +57 -0
- package/dist/devices/dishwasher.js.map +1 -0
- package/dist/devices/evse.d.ts +76 -0
- package/dist/devices/evse.d.ts.map +1 -0
- package/dist/devices/evse.js +74 -10
- package/dist/devices/evse.js.map +1 -0
- package/dist/devices/export.d.ts +17 -0
- package/dist/devices/export.d.ts.map +1 -0
- package/dist/devices/export.js +5 -0
- package/dist/devices/export.js.map +1 -0
- package/dist/devices/extractorHood.d.ts +46 -0
- package/dist/devices/extractorHood.d.ts.map +1 -0
- package/dist/devices/extractorHood.js +43 -0
- package/dist/devices/extractorHood.js.map +1 -0
- package/dist/devices/heatPump.d.ts +47 -0
- package/dist/devices/heatPump.d.ts.map +1 -0
- package/dist/devices/heatPump.js +50 -2
- package/dist/devices/heatPump.js.map +1 -0
- package/dist/devices/laundryDryer.d.ts +67 -0
- package/dist/devices/laundryDryer.d.ts.map +1 -0
- package/dist/devices/laundryDryer.js +62 -3
- package/dist/devices/laundryDryer.js.map +1 -0
- package/dist/devices/laundryWasher.d.ts +81 -0
- package/dist/devices/laundryWasher.d.ts.map +1 -0
- package/dist/devices/laundryWasher.js +70 -4
- package/dist/devices/laundryWasher.js.map +1 -0
- package/dist/devices/microwaveOven.d.ts +168 -0
- package/dist/devices/microwaveOven.d.ts.map +1 -0
- package/dist/devices/microwaveOven.js +88 -5
- package/dist/devices/microwaveOven.js.map +1 -0
- package/dist/devices/oven.d.ts +105 -0
- package/dist/devices/oven.d.ts.map +1 -0
- package/dist/devices/oven.js +85 -0
- package/dist/devices/oven.js.map +1 -0
- package/dist/devices/refrigerator.d.ts +118 -0
- package/dist/devices/refrigerator.d.ts.map +1 -0
- package/dist/devices/refrigerator.js +102 -0
- package/dist/devices/refrigerator.js.map +1 -0
- package/dist/devices/roboticVacuumCleaner.d.ts +112 -0
- package/dist/devices/roboticVacuumCleaner.d.ts.map +1 -0
- package/dist/devices/roboticVacuumCleaner.js +100 -9
- package/dist/devices/roboticVacuumCleaner.js.map +1 -0
- package/dist/devices/solarPower.d.ts +40 -0
- package/dist/devices/solarPower.d.ts.map +1 -0
- package/dist/devices/solarPower.js +38 -0
- package/dist/devices/solarPower.js.map +1 -0
- package/dist/devices/speaker.d.ts +87 -0
- package/dist/devices/speaker.d.ts.map +1 -0
- package/dist/devices/speaker.js +84 -0
- package/dist/devices/speaker.js.map +1 -0
- package/dist/devices/temperatureControl.d.ts +166 -0
- package/dist/devices/temperatureControl.d.ts.map +1 -0
- package/dist/devices/temperatureControl.js +24 -3
- package/dist/devices/temperatureControl.js.map +1 -0
- package/dist/devices/waterHeater.d.ts +111 -0
- package/dist/devices/waterHeater.d.ts.map +1 -0
- package/dist/devices/waterHeater.js +82 -2
- package/dist/devices/waterHeater.js.map +1 -0
- package/dist/dgram/coap.d.ts +205 -0
- package/dist/dgram/coap.d.ts.map +1 -0
- package/dist/dgram/coap.js +126 -13
- package/dist/dgram/coap.js.map +1 -0
- package/dist/dgram/dgram.d.ts +141 -0
- package/dist/dgram/dgram.d.ts.map +1 -0
- package/dist/dgram/dgram.js +114 -2
- package/dist/dgram/dgram.js.map +1 -0
- package/dist/dgram/mb_coap.d.ts +24 -0
- package/dist/dgram/mb_coap.d.ts.map +1 -0
- package/dist/dgram/mb_coap.js +41 -3
- package/dist/dgram/mb_coap.js.map +1 -0
- package/dist/dgram/mb_mdns.d.ts +24 -0
- package/dist/dgram/mb_mdns.d.ts.map +1 -0
- package/dist/dgram/mb_mdns.js +80 -15
- package/dist/dgram/mb_mdns.js.map +1 -0
- package/dist/dgram/mdns.d.ts +290 -0
- package/dist/dgram/mdns.d.ts.map +1 -0
- package/dist/dgram/mdns.js +299 -137
- package/dist/dgram/mdns.js.map +1 -0
- package/dist/dgram/multicast.d.ts +67 -0
- package/dist/dgram/multicast.d.ts.map +1 -0
- package/dist/dgram/multicast.js +62 -1
- package/dist/dgram/multicast.js.map +1 -0
- package/dist/dgram/unicast.d.ts +56 -0
- package/dist/dgram/unicast.d.ts.map +1 -0
- package/dist/dgram/unicast.js +54 -0
- package/dist/dgram/unicast.js.map +1 -0
- package/dist/frontend.d.ts +238 -0
- package/dist/frontend.d.ts.map +1 -0
- package/dist/frontend.js +455 -35
- package/dist/frontend.js.map +1 -0
- package/dist/frontendTypes.d.ts +529 -0
- package/dist/frontendTypes.d.ts.map +1 -0
- package/dist/frontendTypes.js +45 -0
- package/dist/frontendTypes.js.map +1 -0
- package/dist/helpers.d.ts +48 -0
- package/dist/helpers.d.ts.map +1 -0
- package/dist/helpers.js +53 -0
- package/dist/helpers.js.map +1 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +25 -0
- package/dist/index.js.map +1 -0
- package/dist/jestutils/export.d.ts +2 -0
- package/dist/jestutils/export.d.ts.map +1 -0
- package/dist/jestutils/export.js +1 -0
- package/dist/jestutils/export.js.map +1 -0
- package/dist/jestutils/jestHelpers.d.ts +345 -0
- package/dist/jestutils/jestHelpers.d.ts.map +1 -0
- package/dist/jestutils/jestHelpers.js +371 -14
- package/dist/jestutils/jestHelpers.js.map +1 -0
- package/dist/logger/export.d.ts +2 -0
- package/dist/logger/export.d.ts.map +1 -0
- package/dist/logger/export.js +1 -0
- package/dist/logger/export.js.map +1 -0
- package/dist/matter/behaviors.d.ts +2 -0
- package/dist/matter/behaviors.d.ts.map +1 -0
- package/dist/matter/behaviors.js +2 -0
- package/dist/matter/behaviors.js.map +1 -0
- package/dist/matter/clusters.d.ts +2 -0
- package/dist/matter/clusters.d.ts.map +1 -0
- package/dist/matter/clusters.js +2 -0
- package/dist/matter/clusters.js.map +1 -0
- package/dist/matter/devices.d.ts +2 -0
- package/dist/matter/devices.d.ts.map +1 -0
- package/dist/matter/devices.js +2 -0
- package/dist/matter/devices.js.map +1 -0
- package/dist/matter/endpoints.d.ts +2 -0
- package/dist/matter/endpoints.d.ts.map +1 -0
- package/dist/matter/endpoints.js +2 -0
- package/dist/matter/endpoints.js.map +1 -0
- package/dist/matter/export.d.ts +5 -0
- package/dist/matter/export.d.ts.map +1 -0
- package/dist/matter/export.js +3 -0
- package/dist/matter/export.js.map +1 -0
- package/dist/matter/types.d.ts +3 -0
- package/dist/matter/types.d.ts.map +1 -0
- package/dist/matter/types.js +3 -0
- package/dist/matter/types.js.map +1 -0
- package/dist/matterNode.d.ts +342 -0
- package/dist/matterNode.d.ts.map +1 -0
- package/dist/matterNode.js +369 -8
- package/dist/matterNode.js.map +1 -0
- package/dist/matterbridge.d.ts +492 -0
- package/dist/matterbridge.d.ts.map +1 -0
- package/dist/matterbridge.js +811 -46
- package/dist/matterbridge.js.map +1 -0
- package/dist/matterbridgeAccessoryPlatform.d.ts +41 -0
- package/dist/matterbridgeAccessoryPlatform.d.ts.map +1 -0
- package/dist/matterbridgeAccessoryPlatform.js +38 -0
- package/dist/matterbridgeAccessoryPlatform.js.map +1 -0
- package/dist/matterbridgeBehaviors.d.ts +2404 -0
- package/dist/matterbridgeBehaviors.d.ts.map +1 -0
- package/dist/matterbridgeBehaviors.js +68 -5
- package/dist/matterbridgeBehaviors.js.map +1 -0
- package/dist/matterbridgeDeviceTypes.d.ts +698 -0
- package/dist/matterbridgeDeviceTypes.d.ts.map +1 -0
- package/dist/matterbridgeDeviceTypes.js +635 -14
- package/dist/matterbridgeDeviceTypes.js.map +1 -0
- package/dist/matterbridgeDynamicPlatform.d.ts +41 -0
- package/dist/matterbridgeDynamicPlatform.d.ts.map +1 -0
- package/dist/matterbridgeDynamicPlatform.js +38 -0
- package/dist/matterbridgeDynamicPlatform.js.map +1 -0
- package/dist/matterbridgeEndpoint.d.ts +1507 -0
- package/dist/matterbridgeEndpoint.d.ts.map +1 -0
- package/dist/matterbridgeEndpoint.js +1444 -53
- package/dist/matterbridgeEndpoint.js.map +1 -0
- package/dist/matterbridgeEndpointHelpers.d.ts +787 -0
- package/dist/matterbridgeEndpointHelpers.d.ts.map +1 -0
- package/dist/matterbridgeEndpointHelpers.js +483 -20
- package/dist/matterbridgeEndpointHelpers.js.map +1 -0
- package/dist/matterbridgeEndpointTypes.d.ts +166 -0
- package/dist/matterbridgeEndpointTypes.d.ts.map +1 -0
- package/dist/matterbridgeEndpointTypes.js +25 -0
- package/dist/matterbridgeEndpointTypes.js.map +1 -0
- package/dist/matterbridgePlatform.d.ts +539 -0
- package/dist/matterbridgePlatform.d.ts.map +1 -0
- package/dist/matterbridgePlatform.js +451 -1
- package/dist/matterbridgePlatform.js.map +1 -0
- package/dist/matterbridgeTypes.d.ts +251 -0
- package/dist/matterbridgeTypes.d.ts.map +1 -0
- package/dist/matterbridgeTypes.js +26 -0
- package/dist/matterbridgeTypes.js.map +1 -0
- package/dist/pluginManager.d.ts +372 -0
- package/dist/pluginManager.d.ts.map +1 -0
- package/dist/pluginManager.js +341 -5
- package/dist/pluginManager.js.map +1 -0
- package/dist/shelly.d.ts +181 -0
- package/dist/shelly.d.ts.map +1 -0
- package/dist/shelly.js +178 -7
- package/dist/shelly.js.map +1 -0
- package/dist/storage/export.d.ts +2 -0
- package/dist/storage/export.d.ts.map +1 -0
- package/dist/storage/export.js +1 -0
- package/dist/storage/export.js.map +1 -0
- package/dist/update.d.ts +84 -0
- package/dist/update.d.ts.map +1 -0
- package/dist/update.js +93 -1
- package/dist/update.js.map +1 -0
- package/dist/utils/colorUtils.d.ts +101 -0
- package/dist/utils/colorUtils.d.ts.map +1 -0
- package/dist/utils/colorUtils.js +97 -2
- package/dist/utils/colorUtils.js.map +1 -0
- package/dist/utils/commandLine.d.ts +66 -0
- package/dist/utils/commandLine.d.ts.map +1 -0
- package/dist/utils/commandLine.js +60 -0
- package/dist/utils/commandLine.js.map +1 -0
- package/dist/utils/copyDirectory.d.ts +35 -0
- package/dist/utils/copyDirectory.d.ts.map +1 -0
- package/dist/utils/copyDirectory.js +37 -0
- package/dist/utils/copyDirectory.js.map +1 -0
- package/dist/utils/createDirectory.d.ts +34 -0
- package/dist/utils/createDirectory.d.ts.map +1 -0
- package/dist/utils/createDirectory.js +33 -0
- package/dist/utils/createDirectory.js.map +1 -0
- package/dist/utils/createZip.d.ts +39 -0
- package/dist/utils/createZip.d.ts.map +1 -0
- package/dist/utils/createZip.js +47 -2
- package/dist/utils/createZip.js.map +1 -0
- package/dist/utils/deepCopy.d.ts +32 -0
- package/dist/utils/deepCopy.d.ts.map +1 -0
- package/dist/utils/deepCopy.js +39 -0
- package/dist/utils/deepCopy.js.map +1 -0
- package/dist/utils/deepEqual.d.ts +54 -0
- package/dist/utils/deepEqual.d.ts.map +1 -0
- package/dist/utils/deepEqual.js +72 -1
- package/dist/utils/deepEqual.js.map +1 -0
- package/dist/utils/error.d.ts +45 -0
- package/dist/utils/error.d.ts.map +1 -0
- package/dist/utils/error.js +42 -0
- package/dist/utils/error.js.map +1 -0
- package/dist/utils/export.d.ts +13 -0
- package/dist/utils/export.d.ts.map +1 -0
- package/dist/utils/export.js +1 -0
- package/dist/utils/export.js.map +1 -0
- package/dist/utils/format.d.ts +53 -0
- package/dist/utils/format.d.ts.map +1 -0
- package/dist/utils/format.js +49 -0
- package/dist/utils/format.js.map +1 -0
- package/dist/utils/hex.d.ts +89 -0
- package/dist/utils/hex.d.ts.map +1 -0
- package/dist/utils/hex.js +124 -0
- package/dist/utils/hex.js.map +1 -0
- package/dist/utils/inspector.d.ts +87 -0
- package/dist/utils/inspector.d.ts.map +1 -0
- package/dist/utils/inspector.js +69 -1
- package/dist/utils/inspector.js.map +1 -0
- package/dist/utils/isvalid.d.ts +103 -0
- package/dist/utils/isvalid.d.ts.map +1 -0
- package/dist/utils/isvalid.js +101 -0
- package/dist/utils/isvalid.js.map +1 -0
- package/dist/utils/network.d.ts +111 -0
- package/dist/utils/network.d.ts.map +1 -0
- package/dist/utils/network.js +96 -5
- package/dist/utils/network.js.map +1 -0
- package/dist/utils/spawn.d.ts +33 -0
- package/dist/utils/spawn.d.ts.map +1 -0
- package/dist/utils/spawn.js +71 -1
- package/dist/utils/spawn.js.map +1 -0
- package/dist/utils/tracker.d.ts +108 -0
- package/dist/utils/tracker.d.ts.map +1 -0
- package/dist/utils/tracker.js +64 -1
- package/dist/utils/tracker.js.map +1 -0
- package/dist/utils/wait.d.ts +54 -0
- package/dist/utils/wait.d.ts.map +1 -0
- package/dist/utils/wait.js +60 -8
- package/dist/utils/wait.js.map +1 -0
- package/dist/workerGlobalPrefix.d.ts +25 -0
- package/dist/workerGlobalPrefix.d.ts.map +1 -0
- package/dist/workerGlobalPrefix.js +37 -5
- package/dist/workerGlobalPrefix.js.map +1 -0
- package/dist/workerTypes.d.ts +52 -0
- package/dist/workerTypes.d.ts.map +1 -0
- package/dist/workerTypes.js +24 -0
- package/dist/workerTypes.js.map +1 -0
- package/dist/workers.d.ts +69 -0
- package/dist/workers.d.ts.map +1 -0
- package/dist/workers.js +68 -4
- package/dist/workers.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -1
- package/scripts/data_model.mjs +2058 -0
package/dist/utils/format.js
CHANGED
|
@@ -1,9 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @description This file contains the format functions.
|
|
3
|
+
* @file format.ts
|
|
4
|
+
* @author Luca Liguori
|
|
5
|
+
* @created 2025-10-20
|
|
6
|
+
* @version 1.0.0
|
|
7
|
+
* @license Apache-2.0
|
|
8
|
+
*
|
|
9
|
+
* Copyright 2025, 2026, 2027 Luca Liguori.
|
|
10
|
+
*
|
|
11
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
12
|
+
* you may not use this file except in compliance with the License.
|
|
13
|
+
* You may obtain a copy of the License at
|
|
14
|
+
*
|
|
15
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
16
|
+
*
|
|
17
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
18
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
19
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
20
|
+
* See the License for the specific language governing permissions and
|
|
21
|
+
* limitations under the License.
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* Format a timestamp into a human-readable string.
|
|
25
|
+
*
|
|
26
|
+
* @param {number} timestamp - The timestamp in milliseconds since the Unix epoch.
|
|
27
|
+
* @returns {string} - The formatted timestamp.
|
|
28
|
+
*/
|
|
1
29
|
export function formatTimeStamp(timestamp) {
|
|
2
30
|
return `${new Date(timestamp).toLocaleString()}`;
|
|
3
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Format a percentage into a human-readable string.
|
|
34
|
+
*
|
|
35
|
+
* @param {number} percent - The percentage value.
|
|
36
|
+
* @param {number} digits - The number of decimal places.
|
|
37
|
+
* @returns {string} - The formatted percentage.
|
|
38
|
+
*/
|
|
4
39
|
export function formatPercent(percent, digits = 2) {
|
|
5
40
|
return `${percent.toFixed(digits)} %`;
|
|
6
41
|
}
|
|
42
|
+
/**
|
|
43
|
+
* Format bytes into a human-readable string.
|
|
44
|
+
*
|
|
45
|
+
* @param {number} bytes - The number of bytes.
|
|
46
|
+
* @param {number} digits - The number of decimal places.
|
|
47
|
+
* @returns {string} - The formatted byte string.
|
|
48
|
+
*/
|
|
7
49
|
export function formatBytes(bytes, digits = 2) {
|
|
8
50
|
if (bytes === 0)
|
|
9
51
|
return `${bytes.toFixed(digits)} B`;
|
|
@@ -12,6 +54,12 @@ export function formatBytes(bytes, digits = 2) {
|
|
|
12
54
|
const value = bytes / Math.pow(1024, idx);
|
|
13
55
|
return `${value.toFixed(digits)} ${units[idx]}`;
|
|
14
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Function to format system uptime with only the most significant unit
|
|
59
|
+
*
|
|
60
|
+
* @param {number} seconds - The number of seconds to format
|
|
61
|
+
* @returns {string} The formatted uptime string
|
|
62
|
+
*/
|
|
15
63
|
export function formatUptime(seconds) {
|
|
16
64
|
if (seconds >= 86400) {
|
|
17
65
|
const days = Math.floor(seconds / 86400);
|
|
@@ -27,3 +75,4 @@ export function formatUptime(seconds) {
|
|
|
27
75
|
}
|
|
28
76
|
return `${seconds} second${seconds !== 1 ? 's' : ''}`;
|
|
29
77
|
}
|
|
78
|
+
//# sourceMappingURL=format.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"format.js","sourceRoot":"","sources":["../../src/utils/format.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,SAAiB;IAC/C,OAAO,GAAG,IAAI,IAAI,CAAC,SAAS,CAAC,CAAC,cAAc,EAAE,EAAE,CAAC;AACnD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,aAAa,CAAC,OAAe,EAAE,SAAiB,CAAC;IAC/D,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC;AACxC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,KAAa,EAAE,SAAiB,CAAC;IAC3D,IAAI,KAAK,KAAK,CAAC;QAAE,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC;IACrD,MAAM,KAAK,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAC5C,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACrF,MAAM,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IAC1C,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;AAClD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,OAAe;IAC1C,IAAI,OAAO,IAAI,KAAK,EAAE,CAAC;QACrB,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,CAAC;QACzC,OAAO,GAAG,IAAI,OAAO,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;IAC/C,CAAC;IACD,IAAI,OAAO,IAAI,IAAI,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;QACzC,OAAO,GAAG,KAAK,QAAQ,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;IAClD,CAAC;IACD,IAAI,OAAO,IAAI,EAAE,EAAE,CAAC;QAClB,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC;QACzC,OAAO,GAAG,OAAO,UAAU,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;IACxD,CAAC;IACD,OAAO,GAAG,OAAO,UAAU,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;AACxD,CAAC"}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file contains the hex functions.
|
|
3
|
+
*
|
|
4
|
+
* @file hex.ts
|
|
5
|
+
* @author Luca Liguori
|
|
6
|
+
* @created 2025-05-06
|
|
7
|
+
* @version 1.0.0
|
|
8
|
+
* @license Apache-2.0
|
|
9
|
+
*
|
|
10
|
+
* Copyright 2025, 2026, 2027 Luca Liguori.
|
|
11
|
+
*
|
|
12
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
13
|
+
* you may not use this file except in compliance with the License.
|
|
14
|
+
* You may obtain a copy of the License at
|
|
15
|
+
*
|
|
16
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
17
|
+
*
|
|
18
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
19
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
20
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
21
|
+
* See the License for the specific language governing permissions and
|
|
22
|
+
* limitations under the License.
|
|
23
|
+
*/
|
|
24
|
+
/**
|
|
25
|
+
* Converts an ArrayBuffer or Uint8Array to a hexadecimal string.
|
|
26
|
+
*
|
|
27
|
+
* Accepts any {ArrayBufferLike} input: a raw ArrayBuffer (binary data storage) or
|
|
28
|
+
* a Uint8Array (TypedArray view over an ArrayBuffer). While an ArrayBuffer holds
|
|
29
|
+
* the raw memory, a Uint8Array is a typed view into that memory, letting you access
|
|
30
|
+
* its bytes directly. This function normalizes both by creating a Uint8Array view
|
|
31
|
+
* before conversion.
|
|
32
|
+
*
|
|
33
|
+
* @param {ArrayBufferLike} buffer - The buffer or typed-array view to convert.
|
|
34
|
+
* @returns {string} A lowercase hex string representation of the buffer's bytes.
|
|
35
|
+
*
|
|
36
|
+
* @throws {TypeError} If the input is not an ArrayBuffer or ArrayBufferView.
|
|
37
|
+
*/
|
|
38
|
+
export declare function bufferToHex(buffer: ArrayBufferLike): string;
|
|
39
|
+
/**
|
|
40
|
+
* Converts a hexadecimal string to a Uint8Array.
|
|
41
|
+
*
|
|
42
|
+
* @param {string} hex - The hex string to convert. Can include uppercase or lowercase characters.
|
|
43
|
+
* @returns {Uint8Array} A Uint8Array representing the corresponding binary data.
|
|
44
|
+
*
|
|
45
|
+
* @throws {TypeError} If the input is not a string.
|
|
46
|
+
* @throws {Error} If the input length is odd or contains non-hex characters.
|
|
47
|
+
*/
|
|
48
|
+
export declare function hexToBuffer(hex: string): Uint8Array;
|
|
49
|
+
/**
|
|
50
|
+
* Converts a PEM (Privacy-Enhanced Mail) formatted string to a Uint8Array.
|
|
51
|
+
*
|
|
52
|
+
* PEM format is a base64-encoded format commonly used for cryptographic keys and certificates,
|
|
53
|
+
* wrapped with header and footer lines like "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----".
|
|
54
|
+
* This function extracts the base64 content and converts it to binary data using Node.js Buffer API.
|
|
55
|
+
*
|
|
56
|
+
* @param {string} pem - The PEM formatted string to convert.
|
|
57
|
+
* @param {boolean} validate - Whether to validate the PEM content using Node.js crypto module. Default is false.
|
|
58
|
+
* @returns {Uint8Array} A Uint8Array representing the decoded binary data.
|
|
59
|
+
*
|
|
60
|
+
* @throws {TypeError} If the input is not a string.
|
|
61
|
+
* @throws {Error} If the PEM format is invalid, contains invalid base64 characters, or validation fails.
|
|
62
|
+
*/
|
|
63
|
+
export declare function pemToBuffer(pem: string, validate?: boolean): Uint8Array;
|
|
64
|
+
/**
|
|
65
|
+
* Extracts the raw 32-byte private key scalar from an EC private key PEM.
|
|
66
|
+
*
|
|
67
|
+
* This function parses an EC private key in PEM format and extracts the raw
|
|
68
|
+
* 32-byte private scalar (the "d" value) used in elliptic curve cryptography.
|
|
69
|
+
* This is the actual secret key material.
|
|
70
|
+
*
|
|
71
|
+
* @param {string} pemPrivateKey - The EC private key in PEM format
|
|
72
|
+
* @returns {Uint8Array} The raw 32-byte private key scalar
|
|
73
|
+
* @throws {Error} If the input is not a valid EC private key PEM
|
|
74
|
+
*
|
|
75
|
+
* @example
|
|
76
|
+
* ```typescript
|
|
77
|
+
* const pemKey = `-----BEGIN EC PRIVATE KEY-----
|
|
78
|
+
* MHcCAQEEIFBxqFkUxMoN2JkUXLFeiZnLNUpftjLi0sKMbZ6uajHXoAoGCCqGSM49
|
|
79
|
+
* AwEHoUQDQgAEcJ3eH/rG3zf9WmqMjh5eBSkeXz3Cb4Fig1rTosfHmgyjx/WnLPEe
|
|
80
|
+
* BF4SHvLo0G2COJEHa/VDE5EiKWO9ZR6AOQ==
|
|
81
|
+
* -----END EC PRIVATE KEY-----`;
|
|
82
|
+
*
|
|
83
|
+
* const rawKey = extractPrivateKeyRaw(pemKey);
|
|
84
|
+
* console.log(rawKey.length); // 32
|
|
85
|
+
* console.log(bufferToHex(rawKey)); // hex representation of the private scalar
|
|
86
|
+
* ```
|
|
87
|
+
*/
|
|
88
|
+
export declare function extractPrivateKeyRaw(pemPrivateKey: string): Uint8Array;
|
|
89
|
+
//# sourceMappingURL=hex.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hex.d.ts","sourceRoot":"","sources":["../../src/utils/hex.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAIH;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,eAAe,GAAG,MAAM,CAa3D;AAED;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAgCnD;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,GAAE,OAAe,GAAG,UAAU,CAoG9E;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,oBAAoB,CAAC,aAAa,EAAE,MAAM,GAAG,UAAU,CAgCtE"}
|
package/dist/utils/hex.js
CHANGED
|
@@ -1,39 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file contains the hex functions.
|
|
3
|
+
*
|
|
4
|
+
* @file hex.ts
|
|
5
|
+
* @author Luca Liguori
|
|
6
|
+
* @created 2025-05-06
|
|
7
|
+
* @version 1.0.0
|
|
8
|
+
* @license Apache-2.0
|
|
9
|
+
*
|
|
10
|
+
* Copyright 2025, 2026, 2027 Luca Liguori.
|
|
11
|
+
*
|
|
12
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
13
|
+
* you may not use this file except in compliance with the License.
|
|
14
|
+
* You may obtain a copy of the License at
|
|
15
|
+
*
|
|
16
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
17
|
+
*
|
|
18
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
19
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
20
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
21
|
+
* See the License for the specific language governing permissions and
|
|
22
|
+
* limitations under the License.
|
|
23
|
+
*/
|
|
1
24
|
import { createPublicKey, createPrivateKey, X509Certificate } from 'node:crypto';
|
|
25
|
+
/**
|
|
26
|
+
* Converts an ArrayBuffer or Uint8Array to a hexadecimal string.
|
|
27
|
+
*
|
|
28
|
+
* Accepts any {ArrayBufferLike} input: a raw ArrayBuffer (binary data storage) or
|
|
29
|
+
* a Uint8Array (TypedArray view over an ArrayBuffer). While an ArrayBuffer holds
|
|
30
|
+
* the raw memory, a Uint8Array is a typed view into that memory, letting you access
|
|
31
|
+
* its bytes directly. This function normalizes both by creating a Uint8Array view
|
|
32
|
+
* before conversion.
|
|
33
|
+
*
|
|
34
|
+
* @param {ArrayBufferLike} buffer - The buffer or typed-array view to convert.
|
|
35
|
+
* @returns {string} A lowercase hex string representation of the buffer's bytes.
|
|
36
|
+
*
|
|
37
|
+
* @throws {TypeError} If the input is not an ArrayBuffer or ArrayBufferView.
|
|
38
|
+
*/
|
|
2
39
|
export function bufferToHex(buffer) {
|
|
40
|
+
// Check if the input is an ArrayBuffer or ArrayBufferView
|
|
3
41
|
if (!(buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer))) {
|
|
4
42
|
throw new TypeError('Expected input to be an ArrayBuffer or ArrayBufferView');
|
|
5
43
|
}
|
|
44
|
+
// Create a Uint8Array view over the buffer
|
|
6
45
|
const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
|
|
46
|
+
// Convert each byte to 2-digit hex
|
|
7
47
|
return Array.from(bytes)
|
|
8
48
|
.map((byte) => byte.toString(16).padStart(2, '0'))
|
|
9
49
|
.join('');
|
|
10
50
|
}
|
|
51
|
+
/**
|
|
52
|
+
* Converts a hexadecimal string to a Uint8Array.
|
|
53
|
+
*
|
|
54
|
+
* @param {string} hex - The hex string to convert. Can include uppercase or lowercase characters.
|
|
55
|
+
* @returns {Uint8Array} A Uint8Array representing the corresponding binary data.
|
|
56
|
+
*
|
|
57
|
+
* @throws {TypeError} If the input is not a string.
|
|
58
|
+
* @throws {Error} If the input length is odd or contains non-hex characters.
|
|
59
|
+
*/
|
|
11
60
|
export function hexToBuffer(hex) {
|
|
61
|
+
// Ensure the input is a string
|
|
12
62
|
if (typeof hex !== 'string') {
|
|
13
63
|
throw new TypeError('Expected a string for hex input');
|
|
14
64
|
}
|
|
65
|
+
// Trim any whitespace from the input string
|
|
15
66
|
const cleaned = hex.trim();
|
|
67
|
+
// Check if the length of the hex string is even
|
|
16
68
|
if (cleaned.length % 2 !== 0) {
|
|
17
69
|
throw new Error('Invalid hex string length, must be even');
|
|
18
70
|
}
|
|
71
|
+
// Validate that the string contains only valid hex characters
|
|
19
72
|
if (!/^[0-9a-fA-F]*$/.test(cleaned)) {
|
|
20
73
|
throw new Error('Invalid hex string, contains non-hex characters');
|
|
21
74
|
}
|
|
75
|
+
// Calculate the length of the resulting Uint8Array
|
|
22
76
|
const length = cleaned.length / 2;
|
|
77
|
+
// Create a Uint8Array to hold the binary data
|
|
23
78
|
const result = new Uint8Array(length);
|
|
79
|
+
// Convert each pair of hex characters into a byte
|
|
24
80
|
for (let i = 0; i < length; i++) {
|
|
25
81
|
result[i] = parseInt(cleaned.substr(i * 2, 2), 16);
|
|
26
82
|
}
|
|
83
|
+
// Return the resulting Uint8Array
|
|
27
84
|
return result;
|
|
28
85
|
}
|
|
86
|
+
/**
|
|
87
|
+
* Converts a PEM (Privacy-Enhanced Mail) formatted string to a Uint8Array.
|
|
88
|
+
*
|
|
89
|
+
* PEM format is a base64-encoded format commonly used for cryptographic keys and certificates,
|
|
90
|
+
* wrapped with header and footer lines like "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----".
|
|
91
|
+
* This function extracts the base64 content and converts it to binary data using Node.js Buffer API.
|
|
92
|
+
*
|
|
93
|
+
* @param {string} pem - The PEM formatted string to convert.
|
|
94
|
+
* @param {boolean} validate - Whether to validate the PEM content using Node.js crypto module. Default is false.
|
|
95
|
+
* @returns {Uint8Array} A Uint8Array representing the decoded binary data.
|
|
96
|
+
*
|
|
97
|
+
* @throws {TypeError} If the input is not a string.
|
|
98
|
+
* @throws {Error} If the PEM format is invalid, contains invalid base64 characters, or validation fails.
|
|
99
|
+
*/
|
|
29
100
|
export function pemToBuffer(pem, validate = false) {
|
|
101
|
+
// Ensure the input is a string
|
|
30
102
|
if (typeof pem !== 'string') {
|
|
31
103
|
throw new TypeError('Expected a string for PEM input');
|
|
32
104
|
}
|
|
105
|
+
// Trim whitespace from the input
|
|
33
106
|
const cleaned = pem.trim();
|
|
107
|
+
// Check if the string appears to be in PEM format
|
|
34
108
|
if (!cleaned.includes('-----BEGIN') || !cleaned.includes('-----END')) {
|
|
35
109
|
throw new Error('Invalid PEM format: missing BEGIN/END markers');
|
|
36
110
|
}
|
|
111
|
+
// Extract the base64 content between the header and footer
|
|
37
112
|
const lines = cleaned.split('\n');
|
|
38
113
|
const base64Lines = [];
|
|
39
114
|
let inContent = false;
|
|
@@ -54,65 +129,114 @@ export function pemToBuffer(pem, validate = false) {
|
|
|
54
129
|
if (base64Lines.length === 0) {
|
|
55
130
|
throw new Error('Invalid PEM format: no content found between BEGIN/END markers');
|
|
56
131
|
}
|
|
132
|
+
// Join all base64 lines together
|
|
57
133
|
const base64String = base64Lines.join('');
|
|
134
|
+
// Validate base64 string format
|
|
58
135
|
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64String)) {
|
|
59
136
|
throw new Error('Invalid PEM format: contains invalid base64 characters');
|
|
60
137
|
}
|
|
61
138
|
try {
|
|
139
|
+
// Use Node.js Buffer API instead of legacy atob()
|
|
62
140
|
const buffer = Buffer.from(base64String, 'base64');
|
|
141
|
+
// Convert Buffer to Uint8Array
|
|
63
142
|
const result = new Uint8Array(buffer);
|
|
143
|
+
// Validate PEM content using Node.js crypto module if requested
|
|
64
144
|
if (validate) {
|
|
65
145
|
try {
|
|
146
|
+
// Determine PEM type from the header and validate accordingly
|
|
66
147
|
const pemType = cleaned.match(/-----BEGIN\s+([^-]+)-----/)?.[1]?.trim();
|
|
67
148
|
if (pemType?.includes('CERTIFICATE')) {
|
|
149
|
+
// Use X509Certificate for robust certificate validation
|
|
68
150
|
const cert = new X509Certificate(pem);
|
|
151
|
+
// Check validity period
|
|
69
152
|
if (cert.validFrom && cert.validTo) {
|
|
70
153
|
const now = Date.now();
|
|
71
154
|
const from = Date.parse(cert.validFrom);
|
|
72
155
|
const to = Date.parse(cert.validTo);
|
|
156
|
+
// istanbul ignore next if
|
|
73
157
|
if (now < from || now > to) {
|
|
74
158
|
throw new Error('Certificate is not currently valid');
|
|
75
159
|
}
|
|
76
160
|
}
|
|
161
|
+
// Check subject/issuer fields
|
|
162
|
+
// istanbul ignore next if
|
|
77
163
|
if (!cert.subject || !cert.issuer) {
|
|
78
164
|
throw new Error('Certificate missing subject or issuer');
|
|
79
165
|
}
|
|
166
|
+
// Optionally check signature (not possible without CA chain)
|
|
80
167
|
}
|
|
81
168
|
else if (pemType?.includes('PRIVATE KEY')) {
|
|
169
|
+
// For private keys, try to create a private key
|
|
82
170
|
createPrivateKey({ key: pem, format: 'pem' });
|
|
83
171
|
}
|
|
84
172
|
else if (pemType?.includes('PUBLIC KEY')) {
|
|
173
|
+
// For public keys, try to create a public key
|
|
85
174
|
createPublicKey({ key: pem, format: 'pem' });
|
|
86
175
|
}
|
|
176
|
+
// If no specific type is detected, skip validation
|
|
87
177
|
}
|
|
88
178
|
catch (validationError) {
|
|
179
|
+
// istanbul ignore next
|
|
89
180
|
throw new Error(`PEM validation failed: ${validationError instanceof Error ? validationError.message : String(validationError)}`);
|
|
90
181
|
}
|
|
91
182
|
}
|
|
92
183
|
return result;
|
|
93
184
|
}
|
|
94
185
|
catch (error) {
|
|
186
|
+
// istanbul ignore next
|
|
95
187
|
throw new Error(`Failed to decode base64 content: ${error instanceof Error ? error.message : String(error)}`);
|
|
96
188
|
}
|
|
97
189
|
}
|
|
190
|
+
/**
|
|
191
|
+
* Extracts the raw 32-byte private key scalar from an EC private key PEM.
|
|
192
|
+
*
|
|
193
|
+
* This function parses an EC private key in PEM format and extracts the raw
|
|
194
|
+
* 32-byte private scalar (the "d" value) used in elliptic curve cryptography.
|
|
195
|
+
* This is the actual secret key material.
|
|
196
|
+
*
|
|
197
|
+
* @param {string} pemPrivateKey - The EC private key in PEM format
|
|
198
|
+
* @returns {Uint8Array} The raw 32-byte private key scalar
|
|
199
|
+
* @throws {Error} If the input is not a valid EC private key PEM
|
|
200
|
+
*
|
|
201
|
+
* @example
|
|
202
|
+
* ```typescript
|
|
203
|
+
* const pemKey = `-----BEGIN EC PRIVATE KEY-----
|
|
204
|
+
* MHcCAQEEIFBxqFkUxMoN2JkUXLFeiZnLNUpftjLi0sKMbZ6uajHXoAoGCCqGSM49
|
|
205
|
+
* AwEHoUQDQgAEcJ3eH/rG3zf9WmqMjh5eBSkeXz3Cb4Fig1rTosfHmgyjx/WnLPEe
|
|
206
|
+
* BF4SHvLo0G2COJEHa/VDE5EiKWO9ZR6AOQ==
|
|
207
|
+
* -----END EC PRIVATE KEY-----`;
|
|
208
|
+
*
|
|
209
|
+
* const rawKey = extractPrivateKeyRaw(pemKey);
|
|
210
|
+
* console.log(rawKey.length); // 32
|
|
211
|
+
* console.log(bufferToHex(rawKey)); // hex representation of the private scalar
|
|
212
|
+
* ```
|
|
213
|
+
*/
|
|
98
214
|
export function extractPrivateKeyRaw(pemPrivateKey) {
|
|
99
215
|
if (typeof pemPrivateKey !== 'string') {
|
|
100
216
|
throw new TypeError('Expected a string for PEM private key input');
|
|
101
217
|
}
|
|
218
|
+
// Extract the private key block
|
|
102
219
|
const keyBlock = /-----BEGIN (?:EC )?PRIVATE KEY-----[^-]+-----END (?:EC )?PRIVATE KEY-----/s.exec(pemPrivateKey);
|
|
103
220
|
if (!keyBlock) {
|
|
104
221
|
throw new Error('No EC PRIVATE KEY block found in the supplied PEM');
|
|
105
222
|
}
|
|
106
223
|
try {
|
|
224
|
+
// Create a private key object
|
|
107
225
|
const privateKey = createPrivateKey(keyBlock[0]);
|
|
226
|
+
// Export as PKCS#8 DER format
|
|
108
227
|
const pkcs8Der = privateKey.export({ format: 'der', type: 'pkcs8' });
|
|
228
|
+
// For P-256 curves, the private scalar is the last 32 bytes of the PKCS#8 DER
|
|
229
|
+
// istanbul ignore next
|
|
109
230
|
if (pkcs8Der.length < 32) {
|
|
110
231
|
throw new Error('Invalid private key: DER data too short');
|
|
111
232
|
}
|
|
233
|
+
// Extract the last 32 bytes which contain the raw private scalar
|
|
112
234
|
const rawPrivateKey = pkcs8Der.subarray(pkcs8Der.length - 32);
|
|
113
235
|
return new Uint8Array(rawPrivateKey);
|
|
114
236
|
}
|
|
115
237
|
catch (error) {
|
|
238
|
+
// istanbul ignore next
|
|
116
239
|
throw new Error(`Failed to extract private key: ${error instanceof Error ? error.message : String(error)}`);
|
|
117
240
|
}
|
|
118
241
|
}
|
|
242
|
+
//# sourceMappingURL=hex.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hex.js","sourceRoot":"","sources":["../../src/utils/hex.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEjF;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,WAAW,CAAC,MAAuB;IACjD,0DAA0D;IAC1D,IAAI,CAAC,CAAC,MAAM,YAAY,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;QACnE,MAAM,IAAI,SAAS,CAAC,wDAAwD,CAAC,CAAC;IAChF,CAAC;IAED,2CAA2C;IAC3C,MAAM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.0
|
|
8
|
+
* @license Apache-2.0
|
|
9
|
+
*
|
|
10
|
+
* Copyright 2025, 2026, 2027 Luca Liguori.
|
|
11
|
+
*
|
|
12
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
13
|
+
* you may not use this file except in compliance with the License.
|
|
14
|
+
* You may obtain a copy of the License at
|
|
15
|
+
*
|
|
16
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
17
|
+
*
|
|
18
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
19
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
20
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
21
|
+
* See the License for the specific language governing permissions and
|
|
22
|
+
* limitations under the License.
|
|
23
|
+
*/
|
|
24
|
+
import EventEmitter from 'node:events';
|
|
25
|
+
interface InspectorEvents {
|
|
26
|
+
/** Start the inspector */
|
|
27
|
+
start: [];
|
|
28
|
+
/** Stop the inspector */
|
|
29
|
+
stop: [];
|
|
30
|
+
/** Take a heap snapshot */
|
|
31
|
+
snapshot: [];
|
|
32
|
+
/** Heap snapshot done */
|
|
33
|
+
snapshot_done: [];
|
|
34
|
+
/** Run garbage collector */
|
|
35
|
+
gc: [type?: 'major' | 'minor', execution?: 'sync' | 'async'];
|
|
36
|
+
/** Garbage collection done */
|
|
37
|
+
gc_done: [type: 'major' | 'minor', execution: 'sync' | 'async'];
|
|
38
|
+
}
|
|
39
|
+
export declare class Inspector extends EventEmitter<InspectorEvents> {
|
|
40
|
+
private readonly name;
|
|
41
|
+
private readonly debug;
|
|
42
|
+
private readonly verbose;
|
|
43
|
+
private session;
|
|
44
|
+
private snapshotInterval?;
|
|
45
|
+
private snapshotInProgress;
|
|
46
|
+
private log;
|
|
47
|
+
constructor(name?: string, debug?: boolean, verbose?: boolean);
|
|
48
|
+
/**
|
|
49
|
+
* Starts the inspector for heap sampling.
|
|
50
|
+
*
|
|
51
|
+
* This function is called when the -inspect parameter is passed to matterbridge.
|
|
52
|
+
*
|
|
53
|
+
* The -snapshotinterval parameter can be used to set the heap snapshot interval. Default is undefined. Minimum is 30000 ms.
|
|
54
|
+
* The snapshot is saved in the heap_profiles directory that is created in the current working directory.
|
|
55
|
+
* The snapshot can be analyzed using vscode or Chrome DevTools or other tools that support heap snapshots.
|
|
56
|
+
*/
|
|
57
|
+
start(): Promise<void>;
|
|
58
|
+
/**
|
|
59
|
+
* Stops the heap sampling and saves the profile to a file in the heap_profiles directory.
|
|
60
|
+
* This function is called when the inspector is stopped.
|
|
61
|
+
*/
|
|
62
|
+
stop(): Promise<void>;
|
|
63
|
+
/**
|
|
64
|
+
* Takes a heap snapshot and saves it to the file name 'heap_snapshots/<timestamp>.heapsnapshot'.
|
|
65
|
+
* If triggers a full garbage collection before and after taking the snapshot to reduce noise.
|
|
66
|
+
*
|
|
67
|
+
* This function is called periodically based on the -snapshotinterval parameter.
|
|
68
|
+
* The -snapshotinterval parameter must at least 30000 ms.
|
|
69
|
+
* The snapshot is saved in the heap_snapshots directory that is created in the current working directory.
|
|
70
|
+
* The snapshot can be analyzed using vscode or Chrome DevTools or other tools that support heap snapshots.
|
|
71
|
+
*/
|
|
72
|
+
takeHeapSnapshot(): Promise<void>;
|
|
73
|
+
/**
|
|
74
|
+
* Manually trigger garbage collection to free memory (if exposed with --expose-gc)
|
|
75
|
+
*
|
|
76
|
+
* @param {'major' | 'minor'} type - The type of garbage collection to perform ('major' or 'minor'). Default is 'major'.
|
|
77
|
+
* @param {'sync' | 'async'} execution - The execution mode of garbage collection ('sync' or 'async'). Default is 'async'.
|
|
78
|
+
*
|
|
79
|
+
* @remarks
|
|
80
|
+
* - major collection refers to old-generation mark-sweep/mark-compact cycles.
|
|
81
|
+
* - minor collection refers to young-generation collections (scavenges).
|
|
82
|
+
* - sync execution blocks the main thread until GC is complete, which can cause pauses.
|
|
83
|
+
*/
|
|
84
|
+
runGarbageCollector(type?: 'major' | 'minor', execution?: 'sync' | 'async'): void;
|
|
85
|
+
}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B,EAAE,SAAS,GAAE,MAAM,GAAG,OAAiB;CAe7F"}
|
package/dist/utils/inspector.js
CHANGED
|
@@ -1,3 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file contains the Inspector class.
|
|
3
|
+
*
|
|
4
|
+
* @file inspector.ts
|
|
5
|
+
* @author Luca Liguori
|
|
6
|
+
* @created 2025-10-12
|
|
7
|
+
* @version 1.0.0
|
|
8
|
+
* @license Apache-2.0
|
|
9
|
+
*
|
|
10
|
+
* Copyright 2025, 2026, 2027 Luca Liguori.
|
|
11
|
+
*
|
|
12
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
13
|
+
* you may not use this file except in compliance with the License.
|
|
14
|
+
* You may obtain a copy of the License at
|
|
15
|
+
*
|
|
16
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
17
|
+
*
|
|
18
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
19
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
20
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
21
|
+
* See the License for the specific language governing permissions and
|
|
22
|
+
* limitations under the License.
|
|
23
|
+
*/
|
|
24
|
+
/* eslint-disable no-console */
|
|
1
25
|
if (process.argv.includes('--loader') || process.argv.includes('-loader'))
|
|
2
26
|
console.log('\u001B[32mInspector loaded.\u001B[40;0m');
|
|
3
27
|
import EventEmitter from 'node:events';
|
|
@@ -21,7 +45,7 @@ export class Inspector extends EventEmitter {
|
|
|
21
45
|
if (process.argv.includes('--verbose') || process.argv.includes('-verbose')) {
|
|
22
46
|
this.verbose = true;
|
|
23
47
|
}
|
|
24
|
-
this.log = new AnsiLogger({ logName: this.name, logTimestampFormat: 4
|
|
48
|
+
this.log = new AnsiLogger({ logName: this.name, logTimestampFormat: 4 /* TimestampFormat.TIME_MILLIS */, logLevel: this.debug ? "debug" /* LogLevel.DEBUG */ : "info" /* LogLevel.INFO */ });
|
|
25
49
|
this.log.logNameColor = YELLOW;
|
|
26
50
|
this.on('start', () => {
|
|
27
51
|
this.start();
|
|
@@ -36,6 +60,15 @@ export class Inspector extends EventEmitter {
|
|
|
36
60
|
this.runGarbageCollector();
|
|
37
61
|
});
|
|
38
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* Starts the inspector for heap sampling.
|
|
65
|
+
*
|
|
66
|
+
* This function is called when the -inspect parameter is passed to matterbridge.
|
|
67
|
+
*
|
|
68
|
+
* The -snapshotinterval parameter can be used to set the heap snapshot interval. Default is undefined. Minimum is 30000 ms.
|
|
69
|
+
* The snapshot is saved in the heap_profiles directory that is created in the current working directory.
|
|
70
|
+
* The snapshot can be analyzed using vscode or Chrome DevTools or other tools that support heap snapshots.
|
|
71
|
+
*/
|
|
39
72
|
async start() {
|
|
40
73
|
if (this.session) {
|
|
41
74
|
this.log.warn('Inspector session already active.');
|
|
@@ -44,7 +77,9 @@ export class Inspector extends EventEmitter {
|
|
|
44
77
|
const { Session } = await import('node:inspector');
|
|
45
78
|
const { mkdirSync } = await import('node:fs');
|
|
46
79
|
this.log.debug(`Starting heap sampling...`);
|
|
80
|
+
// Create the heap profiles directory if it doesn't exist
|
|
47
81
|
mkdirSync('heap_profiles', { recursive: true });
|
|
82
|
+
// Create the heap snapshots directory if it doesn't exist
|
|
48
83
|
mkdirSync('heap_snapshots', { recursive: true });
|
|
49
84
|
try {
|
|
50
85
|
this.session = new Session();
|
|
@@ -53,6 +88,7 @@ export class Inspector extends EventEmitter {
|
|
|
53
88
|
this.session?.post('HeapProfiler.startSampling', (err) => (err ? reject(err) : resolve()));
|
|
54
89
|
});
|
|
55
90
|
this.log.debug(`Started heap sampling`);
|
|
91
|
+
// Set an interval to take heap snapshots
|
|
56
92
|
const { getIntParameter } = await import('./commandLine.js');
|
|
57
93
|
const interval = getIntParameter('snapshotinterval');
|
|
58
94
|
if (interval && interval >= 30000) {
|
|
@@ -81,6 +117,10 @@ export class Inspector extends EventEmitter {
|
|
|
81
117
|
return;
|
|
82
118
|
}
|
|
83
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Stops the heap sampling and saves the profile to a file in the heap_profiles directory.
|
|
122
|
+
* This function is called when the inspector is stopped.
|
|
123
|
+
*/
|
|
84
124
|
async stop() {
|
|
85
125
|
if (!this.session) {
|
|
86
126
|
this.log.warn('No active inspector session.');
|
|
@@ -91,7 +131,9 @@ export class Inspector extends EventEmitter {
|
|
|
91
131
|
this.log.debug(`Stopping heap sampling...`);
|
|
92
132
|
if (this.snapshotInterval) {
|
|
93
133
|
this.log.debug(`Clearing heap snapshot interval...`);
|
|
134
|
+
// Clear the snapshot interval if it exists
|
|
94
135
|
clearInterval(this.snapshotInterval);
|
|
136
|
+
// Take a final heap snapshot before stopping
|
|
95
137
|
await this.takeHeapSnapshot();
|
|
96
138
|
}
|
|
97
139
|
try {
|
|
@@ -113,6 +155,15 @@ export class Inspector extends EventEmitter {
|
|
|
113
155
|
this.log.debug(`Stopped heap sampling`);
|
|
114
156
|
}
|
|
115
157
|
}
|
|
158
|
+
/**
|
|
159
|
+
* Takes a heap snapshot and saves it to the file name 'heap_snapshots/<timestamp>.heapsnapshot'.
|
|
160
|
+
* If triggers a full garbage collection before and after taking the snapshot to reduce noise.
|
|
161
|
+
*
|
|
162
|
+
* This function is called periodically based on the -snapshotinterval parameter.
|
|
163
|
+
* The -snapshotinterval parameter must at least 30000 ms.
|
|
164
|
+
* The snapshot is saved in the heap_snapshots directory that is created in the current working directory.
|
|
165
|
+
* The snapshot can be analyzed using vscode or Chrome DevTools or other tools that support heap snapshots.
|
|
166
|
+
*/
|
|
116
167
|
async takeHeapSnapshot() {
|
|
117
168
|
if (!this.session) {
|
|
118
169
|
this.log.warn('No active inspector session.');
|
|
@@ -128,6 +179,7 @@ export class Inspector extends EventEmitter {
|
|
|
128
179
|
const path = await import('node:path');
|
|
129
180
|
const safeTimestamp = new Date().toISOString().replace(/[<>:"/\\|?*]/g, '-');
|
|
130
181
|
const filename = path.join('heap_snapshots', `${safeTimestamp}.heapsnapshot`);
|
|
182
|
+
// Trigger a garbage collection before taking the snapshot to reduce noise
|
|
131
183
|
this.runGarbageCollector('minor', 'async');
|
|
132
184
|
this.runGarbageCollector('major', 'async');
|
|
133
185
|
if (this.debug)
|
|
@@ -140,13 +192,16 @@ export class Inspector extends EventEmitter {
|
|
|
140
192
|
};
|
|
141
193
|
stream.once('error', onStreamError);
|
|
142
194
|
const chunksListener = (notification) => {
|
|
195
|
+
// notification.params.chunk is a string; write directly to the stream
|
|
143
196
|
if (!stream.write(notification.params.chunk)) {
|
|
197
|
+
// If backpressure engages, it's fine; the stream will buffer internally. We don't block the inspector.
|
|
144
198
|
}
|
|
145
199
|
};
|
|
146
200
|
this.session.on('HeapProfiler.addHeapSnapshotChunk', chunksListener);
|
|
147
201
|
try {
|
|
148
202
|
await new Promise((resolve) => {
|
|
149
203
|
this.session?.post('HeapProfiler.takeHeapSnapshot', (err) => {
|
|
204
|
+
// Detach chunk listener and close the stream, then perform post-actions
|
|
150
205
|
this.session?.off('HeapProfiler.addHeapSnapshotChunk', chunksListener);
|
|
151
206
|
const finalize = () => {
|
|
152
207
|
if (!err && !streamErrored) {
|
|
@@ -163,6 +218,7 @@ export class Inspector extends EventEmitter {
|
|
|
163
218
|
}
|
|
164
219
|
resolve();
|
|
165
220
|
};
|
|
221
|
+
// End stream and wait for finish or error
|
|
166
222
|
try {
|
|
167
223
|
stream.end(() => finalize());
|
|
168
224
|
}
|
|
@@ -177,6 +233,17 @@ export class Inspector extends EventEmitter {
|
|
|
177
233
|
this.snapshotInProgress = false;
|
|
178
234
|
}
|
|
179
235
|
}
|
|
236
|
+
/**
|
|
237
|
+
* Manually trigger garbage collection to free memory (if exposed with --expose-gc)
|
|
238
|
+
*
|
|
239
|
+
* @param {'major' | 'minor'} type - The type of garbage collection to perform ('major' or 'minor'). Default is 'major'.
|
|
240
|
+
* @param {'sync' | 'async'} execution - The execution mode of garbage collection ('sync' or 'async'). Default is 'async'.
|
|
241
|
+
*
|
|
242
|
+
* @remarks
|
|
243
|
+
* - major collection refers to old-generation mark-sweep/mark-compact cycles.
|
|
244
|
+
* - minor collection refers to young-generation collections (scavenges).
|
|
245
|
+
* - sync execution blocks the main thread until GC is complete, which can cause pauses.
|
|
246
|
+
*/
|
|
180
247
|
runGarbageCollector(type = 'major', execution = 'async') {
|
|
181
248
|
if (global.gc && typeof global.gc === 'function') {
|
|
182
249
|
try {
|
|
@@ -198,3 +265,4 @@ export class Inspector extends EventEmitter {
|
|
|
198
265
|
}
|
|
199
266
|
}
|
|
200
267
|
}
|
|
268
|
+
//# sourceMappingURL=inspector.js.map
|