This commit is contained in:
gongwenxin
2025-08-28 16:20:24 +08:00
parent 61e533cddf
commit 73e887ebf4
1539 changed files with 360926 additions and 0 deletions
+79
View File
@@ -0,0 +1,79 @@
/*!
* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Runtime events
* @mixin @node-red/util_events
*/
const events = new (require("events")).EventEmitter();
const deprecatedEvents = {
"nodes-stopped": "flows:stopped",
"nodes-started": "flows:started"
}
function wrapEventFunction(obj,func) {
events["_"+func] = events[func];
return function(eventName, listener) {
if (deprecatedEvents.hasOwnProperty(eventName)) {
const log = require("@node-red/util").log;
const stack = (new Error().stack).split("\n");
let location = "(unknown)"
// See https://github.com/node-red/node-red/issues/3292
if (stack.length > 2) {
location = stack[2].split("(")[1].slice(0,-1);
}
log.warn(`[RED.events] Deprecated use of "${eventName}" event from "${location}". Use "${deprecatedEvents[eventName]}" instead.`)
}
return events["_"+func].call(events,eventName,listener)
}
}
events.on = wrapEventFunction(events,"on");
events.once = wrapEventFunction(events,"once");
events.addListener = events.on;
module.exports = events;
/**
* Runtime events emitter
* @mixin @node-red/util_events
*/
/**
* Register an event listener for a runtime event
* @name on
* @function
* @memberof @node-red/util_events
* @param {String} eventName - the name of the event to listen to
* @param {Function} listener - the callback function for the event
*/
/**
* Emit an event to all of its registered listeners
* @name emit
* @function
* @memberof @node-red/util_events
* @param {String} eventName - the name of the event to emit
* @param {any} ...args - the arguments to pass in the event
* @return {Boolean} - whether the event had listeners or not
*/
+99
View File
@@ -0,0 +1,99 @@
/*!
* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Run system commands with event-log integration
* @mixin @node-red/util_exec
*/
const child_process = require('child_process');
const events = require("./events");
const util = require('./util');
function logLines(id,type,data) {
events.emit("event-log", {id:id,payload:{ts: Date.now(),data:data,type:type}});
}
module.exports = {
/**
* Run a system command with stdout/err being emitted as 'event-log' events
* on the @node-red/util/events handler.
*
* The main arguments to this function are the same as passed to `child_process.spawn`
*
* @param {String} command - the command to run
* @param {Array} args - arguments for the command
* @param {Object} options - options to pass child_process.spawn
* @param {Boolean} emit - whether to emit events to the event-log for each line of stdout/err
* @return {Promise} A promise that resolves (rc=0) or rejects (rc!=0) when the command completes. The value
* of the promise is an object of the form:
*
* {
* code: <exit code>,
* stdout: <standard output from the command>,
* stderr: <standard error from the command>
* }
* @memberof @node-red/util_exec
*/
run: function(command,args,options,emit) {
var invocationId = util.generateId();
emit && events.emit("event-log", {ts: Date.now(),id:invocationId,payload:{ts: Date.now(),data:command+" "+args.join(" ")}});
return new Promise((resolve, reject) => {
let stdout = "";
let stderr = "";
let child
if (args && options.shell) {
// If we are using a shell, we need to join the args into a single string
// as passing a separate array of args is deprecated in Node 24
command = [command].concat(args).join(" ");
child = child_process.spawn(command, options)
} else {
child = child_process.spawn(command, args, options);
}
child.stdout.on('data', (data) => {
const str = ""+data;
stdout += str;
emit && logLines(invocationId,"out",str);
});
child.stderr.on('data', (data) => {
const str = ""+data;
stderr += str;
emit && logLines(invocationId,"err",str);
});
child.on('error', function(err) {
stderr = err.toString();
emit && logLines(invocationId,"err",stderr);
})
child.on('close', (code) => {
let result = {
code: code,
stdout: stdout,
stderr: stderr
}
emit && events.emit("event-log", {id:invocationId,payload:{ts: Date.now(), data:"rc="+code, end: true}});
if (code === 0) {
resolve(result)
} else {
reject(result);
}
});
})
}
}
+260
View File
@@ -0,0 +1,260 @@
const Log = require("./log.js");
const VALID_HOOKS = [
// Message Routing Path
"onSend",
"preRoute",
"preDeliver",
"postDeliver",
"onReceive",
"postReceive",
"onComplete",
// Module install hooks
"preInstall",
"postInstall",
"preUninstall",
"postUninstall"
]
// Flags for what hooks have handlers registered
let states = { }
// Doubly-LinkedList of hooks by id.
// - hooks[id] points to head of list
// - each list item looks like:
// {
// cb: the callback function
// location: filename/line of code that added the hook
// previousHook: reference to previous hook in list
// nextHook: reference to next hook in list
// removed: a flag that is set if the item was removed
// }
let hooks = { }
// Hooks by label
let labelledHooks = { }
/**
* Runtime hooks engine
*
* The following hooks can be used:
*
* Message sending
* - `onSend` - passed an array of `SendEvent` objects. The messages inside these objects are exactly what the node has passed to `node.send` - meaning there could be duplicate references to the same message object.
* - `preRoute` - passed a `SendEvent`
* - `preDeliver` - passed a `SendEvent`. The local router has identified the node it is going to send to. At this point, the message has been cloned if needed.
* - `postDeliver` - passed a `SendEvent`. The message has been dispatched to be delivered asynchronously (unless the sync delivery flag is set, in which case it would be continue as synchronous delivery)
* - `onReceive` - passed a `ReceiveEvent` when a node is about to receive a message
* - `postReceive` - passed a `ReceiveEvent` when the message has been given to the node's `input` handler(s)
* - `onComplete` - passed a `CompleteEvent` when the node has completed with a message or logged an error
*
* @mixin @node-red/util_hooks
*/
/**
* Register a handler to a named hook
* @memberof @node-red/util_hooks
* @param {String} hookId - the name of the hook to attach to
* @param {Function} callback - the callback function for the hook
*/
function add(hookId, callback) {
let [id, label] = hookId.split(".");
if (VALID_HOOKS.indexOf(id) === -1) {
throw new Error(`Invalid hook '${id}'`);
}
if (label && labelledHooks[label] && labelledHooks[label][id]) {
throw new Error("Hook "+hookId+" already registered")
}
// Get location of calling code
let callModule;
const stack = new Error().stack;
const stackEntries = stack.split("\n").slice(1);//drop 1st line (error message)
const stackEntry2 = stackEntries[1];//get 2nd stack entry
if (stackEntry2) {
try {
if (stackEntry2.indexOf(" (") >= 0) {
callModule = stackEntry2.split("(")[1].slice(0, -1);
} else {
callModule = stackEntry2.split(" ").slice(-1)[0];
}
} catch (error) {
Log.debug(`Unable to determined module when adding hook '${hookId}'. Stack:\n${stackEntries.join("\n")}`);
callModule = "unknown:0:0";
}
} else {
Log.debug(`Unable to determined module when adding hook '${hookId}'. Stack:\n${stackEntries.join("\n")}`);
callModule = "unknown:0:0";
}
Log.debug(`Adding hook '${hookId}' from ${callModule}`);
const hookItem = {cb:callback, location: callModule, previousHook: null, nextHook: null }
let tailItem = hooks[id];
if (tailItem === undefined) {
hooks[id] = hookItem;
} else {
while(tailItem.nextHook !== null) {
tailItem = tailItem.nextHook
}
tailItem.nextHook = hookItem;
hookItem.previousHook = tailItem;
}
if (label) {
labelledHooks[label] = labelledHooks[label]||{};
labelledHooks[label][id] = hookItem;
}
// TODO: get rid of this;
states[id] = true;
}
/**
* Remove a handled from a named hook
* @memberof @node-red/util_hooks
* @param {String} hookId - the name of the hook event to remove - must be `name.label`
*/
function remove(hookId) {
let [id,label] = hookId.split(".");
if ( !label) {
throw new Error("Cannot remove hook without label: "+hookId)
}
Log.debug(`Removing hook '${hookId}'`);
if (labelledHooks[label]) {
if (id === "*") {
// Remove all hooks for this label
let hookList = Object.keys(labelledHooks[label]);
for (let i=0;i<hookList.length;i++) {
removeHook(hookList[i],labelledHooks[label][hookList[i]])
}
delete labelledHooks[label];
} else if (labelledHooks[label][id]) {
removeHook(id,labelledHooks[label][id])
delete labelledHooks[label][id];
if (Object.keys(labelledHooks[label]).length === 0){
delete labelledHooks[label];
}
}
}
}
function removeHook(id,hookItem) {
let previousHook = hookItem.previousHook;
let nextHook = hookItem.nextHook;
if (previousHook) {
previousHook.nextHook = nextHook;
} else {
hooks[id] = nextHook;
}
if (nextHook) {
nextHook.previousHook = previousHook;
}
hookItem.removed = true;
if (!previousHook && !nextHook) {
delete hooks[id];
delete states[id];
}
}
function trigger(hookId, payload, done) {
let hookItem = hooks[hookId];
if (!hookItem) {
if (done) {
done();
return;
} else {
return Promise.resolve();
}
}
if (!done) {
return new Promise((resolve,reject) => {
invokeStack(hookItem,payload,function(err) {
if (err !== undefined && err !== false) {
if (!(err instanceof Error)) {
err = new Error(err);
}
err.hook = hookId
reject(err);
} else {
resolve(err);
}
})
});
} else {
invokeStack(hookItem,payload,done)
}
}
function invokeStack(hookItem,payload,done) {
function callNextHook(err) {
if (!hookItem || err) {
done(err);
return;
}
if (hookItem.removed) {
hookItem = hookItem.nextHook;
callNextHook();
return;
}
const callback = hookItem.cb;
if (callback.length === 1) {
try {
let result = callback(payload);
if (result === false) {
// Halting the flow
done(false);
return
}
if (result && typeof result.then === 'function') {
result.then(handleResolve, callNextHook)
return;
}
hookItem = hookItem.nextHook;
callNextHook();
} catch(err) {
done(err);
return;
}
} else {
try {
callback(payload,handleResolve)
} catch(err) {
done(err);
return;
}
}
}
function handleResolve(result) {
if (result === undefined) {
hookItem = hookItem.nextHook;
callNextHook();
} else {
done(result);
}
}
callNextHook();
}
function clear() {
hooks = {}
labelledHooks = {}
states = {}
}
function has(hookId) {
let [id, label] = hookId.split(".");
if (label) {
return !!(labelledHooks[label] && labelledHooks[label][id])
}
return !!states[id]
}
module.exports = {
has,
clear,
add,
remove,
trigger
}
+255
View File
@@ -0,0 +1,255 @@
/**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* @ignore
**/
/**
* Internationalization utilities
* @mixin @node-red/util_i18n
*/
var i18n = require("i18next");
var path = require("path");
var fs = require("fs");
var defaultLang = "en-US";
var resourceMap = {};
var resourceCache = {};
var initPromise;
/**
* Register multiple message catalogs with i18n.
* @memberof @node-red/util_i18n
*/
function registerMessageCatalogs(catalogs) {
var promises = catalogs.map(function(catalog) {
return registerMessageCatalog(catalog.namespace,catalog.dir,catalog.file).catch(err => {});
});
return Promise.all(promises);
}
/**
* Register a message catalog with i18n.
* @memberof @node-red/util_i18n
*/
async function registerMessageCatalog(namespace,dir,file) {
return initPromise.then(function() {
return new Promise((resolve,reject) => {
resourceMap[namespace] = { basedir:dir, file:file, lngs: []};
fs.readdir(dir,function(err, files) {
if (err) {
resolve();
} else {
files.forEach(function(f) {
if (fs.existsSync(path.join(dir,f,file))) {
resourceMap[namespace].lngs.push(f);
}
});
i18n.loadNamespaces(namespace,function() {
resolve();
});
}
})
});
});
}
function mergeCatalog(fallback,catalog) {
for (var k in fallback) {
if (fallback.hasOwnProperty(k)) {
if (!catalog[k]) {
catalog[k] = fallback[k];
} else if (typeof fallback[k] === 'object') {
mergeCatalog(fallback[k],catalog[k]);
}
}
}
}
function migrateMessageCatalogV3toV4(catalog) {
const keys = Object.keys(catalog)
keys.forEach(key => {
if (typeof catalog[key] === 'object') {
catalog[key] = migrateMessageCatalogV3toV4(catalog[key])
} else if (key.endsWith('_plural')) {
const otherKey = key.replace('_plural', '_other')
if (!catalog[otherKey]) {
catalog[otherKey] = catalog[key]
}
delete catalog[key]
}
})
return catalog
}
async function readFile(lng, ns) {
if (/[^a-z\-]/i.test(lng)) {
throw new Error("Invalid language: "+lng)
}
if (resourceCache[ns] && resourceCache[ns][lng]) {
return resourceCache[ns][lng];
} else if (resourceMap[ns]) {
const file = path.join(resourceMap[ns].basedir, lng, resourceMap[ns].file);
const content = await fs.promises.readFile(file, "utf8");
resourceCache[ns] = resourceCache[ns] || {};
resourceCache[ns][lng] = JSON.parse(content.replace(/^\uFEFF/, ''));
// Message catalogues are in i18next v3 format. That is no longer supported
// by i18next so we need to migrate any catalog to the v4 format.
// This primarily means mapping `FOO_plural` to `FOO_other`
resourceCache[ns][lng] = migrateMessageCatalogV3toV4(resourceCache[ns][lng])
var baseLng = lng.split('-')[0];
if (baseLng !== lng && resourceCache[ns][baseLng]) {
mergeCatalog(resourceCache[ns][baseLng], resourceCache[ns][lng]);
}
if (lng !== defaultLang) {
mergeCatalog(resourceCache[ns][defaultLang], resourceCache[ns][lng]);
}
return resourceCache[ns][lng];
} else {
throw new Error("Unrecognised namespace");
}
}
var MessageFileLoader = {
type: "backend",
init: function (services, backendOptions, i18nextOptions) { },
read: function (lng, ns, callback) {
readFile(lng, ns)
.then(data => callback(null, data))
.catch(err => {
if (/-/.test(lng)) {
// if reading language file fails -> try reading base language (e. g. 'fr' instead of 'fr-FR' or 'de' for 'de-DE')
var baseLng = lng.split('-')[0];
readFile(baseLng, ns).then(baseData => callback(null, baseData)).catch(err => callback(err));
} else {
callback(err);
}
});
}
}
function getCurrentLocale() {
var env = process.env;
for (var name of ['LC_ALL', 'LC_MESSAGES', 'LANG']) {
if (name in env) {
var val = env[name];
return val.substring(0, 2);
}
}
return undefined;
}
function init(settings) {
if (!initPromise) {
initPromise = new Promise((resolve,reject) => {
i18n.use(MessageFileLoader);
var opt = {
// debug: true,
defaultNS: "runtime",
ns: [],
fallbackLng: defaultLang,
keySeparator: ".",
nsSeparator: ":",
interpolation: {
unescapeSuffix: 'HTML',
escapeValue: false,
prefix: '__',
suffix: '__'
}
};
var lang = settings.lang || getCurrentLocale();
if (lang) {
opt.lng = lang;
}
i18n.init(opt ,function() {
resolve();
});
});
}
}
/**
* Gets a message catalog.
* @name catalog
* @function
* @memberof @node-red/util_i18n
*/
function getCatalog(namespace,lang) {
var result = null;
lang = lang || defaultLang;
if (/[^a-z\-]/i.test(lang)) {
throw new Error("Invalid language: "+lng)
}
if (resourceCache.hasOwnProperty(namespace)) {
result = resourceCache[namespace][lang];
if (!result) {
var langParts = lang.split("-");
if (langParts.length == 2) {
result = resourceCache[namespace][langParts[0]];
}
}
}
return result;
}
/**
* Gets a list of languages a given catalog is available in.
* @name availableLanguages
* @function
* @memberof @node-red/util_i18n
*/
function availableLanguages(namespace) {
if (resourceMap.hasOwnProperty(namespace)) {
return resourceMap[namespace].lngs
}
}
var obj = module.exports = {
init: init,
registerMessageCatalog: registerMessageCatalog,
registerMessageCatalogs: registerMessageCatalogs,
catalog: getCatalog,
availableLanguages: availableLanguages,
/**
* The underlying i18n library for when direct access is really needed
*/
i: i18n,
/**
* The default language of the runtime
*/
defaultLang: defaultLang
}
/**
* Perform a message catalog lookup.
* @name _
* @function
* @memberof @node-red/util_i18n
*/
obj['_'] = function() {
//var opts = {};
//if (def) {
// opts.defaultValue = def;
//}
//console.log(arguments);
var res = i18n.t.apply(i18n,arguments);
return res;
}
+265
View File
@@ -0,0 +1,265 @@
/*!
* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Logging utilities
* @mixin @node-red/util_log
*/
var util = require("util");
var EventEmitter = require("events").EventEmitter;
var i18n = require("./i18n");
const chalk = require("chalk");
var levels = {
off: 1,
fatal: 10,
error: 20,
warn: 30,
info: 40,
debug: 50,
trace: 60,
audit: 98,
metric: 99
};
var levelNames = {
10: "fatal",
20: "error",
30: "warn",
40: "info",
50: "debug",
60: "trace",
98: "audit",
99: "metric"
};
var levelColours = {
10: 'red',
20: 'red',
30: 'yellow',
40: '',
50: 'cyan',
60: 'gray',
98: '',
99: ''
};
var logHandlers = [];
var verbose;
var metricsEnabled = false;
var LogHandler = function(settings) {
this.logLevel = settings ? levels[settings.level]||levels.info : levels.info;
this.metricsOn = settings ? settings.metrics||false : false;
this.auditOn = settings ? settings.audit||false : false;
metricsEnabled = metricsEnabled || this.metricsOn;
this.handler = (settings && settings.handler) ? settings.handler(settings) : consoleLogger;
this.on("log",function(msg) {
if (this.shouldReportMessage(msg.level)) {
this.handler(msg);
}
});
}
util.inherits(LogHandler, EventEmitter);
LogHandler.prototype.shouldReportMessage = function(msglevel) {
return (msglevel == log.METRIC && this.metricsOn) ||
(msglevel == log.AUDIT && this.auditOn) ||
msglevel <= this.logLevel;
}
// Older versions of Node-RED used the deprecated util.log function.
// With Node.js 22, use of that function causes warnings. So here we
// are replicating the same format output to ensure we don't break any
// log parsing that happens in the real world.
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const utilLog = function (msg, level) {
const d = new Date();
const time = [
d.getHours().toString().padStart(2, '0'),
d.getMinutes().toString().padStart(2, '0'),
d.getSeconds().toString().padStart(2, '0')
].join(':');
const logLine = `${d.getDate()} ${months[d.getMonth()]} ${time} - ${msg}`
if (levelColours[level]) {
console.log(chalk[levelColours[level]](logLine))
} else {
console.log(logLine)
}
}
var consoleLogger = function(msg) {
if (msg.level == log.METRIC || msg.level == log.AUDIT) {
utilLog("["+levelNames[msg.level]+"] "+JSON.stringify(msg), msg.level);
} else {
if (verbose && msg.msg && msg.msg.stack) {
utilLog("["+levelNames[msg.level]+"] "+(msg.type?"["+msg.type+":"+(msg.name||msg.id)+"] ":"")+msg.msg.stack, msg.level);
} else {
var message = msg.msg;
try {
if (typeof message === 'object' && message !== null && message.toString() === '[object Object]' && message.message) {
message = message.message;
}
} catch(e){
message = 'Exception trying to log: '+util.inspect(message);
}
utilLog("["+levelNames[msg.level]+"] "+(msg.type?"["+msg.type+":"+(msg.name||msg.id)+"] ":"")+message, msg.level);
}
}
}
var log = module.exports = {
FATAL: 10,
ERROR: 20,
WARN: 30,
INFO: 40,
DEBUG: 50,
TRACE: 60,
AUDIT: 98,
METRIC: 99,
init: function(settings) {
metricsEnabled = false;
logHandlers = [];
var loggerSettings = {};
verbose = settings.verbose;
if (settings.logging) {
var keys = Object.keys(settings.logging);
if (keys.length === 0) {
log.addHandler(new LogHandler());
} else {
for (var i=0, l=keys.length; i<l; i++) {
var config = settings.logging[keys[i]];
loggerSettings = config || {};
if ((keys[i] === "console") || config.handler) {
log.addHandler(new LogHandler(loggerSettings));
}
}
}
} else {
log.addHandler(new LogHandler());
}
},
/**
* Add a log handler function
* @memberof @node-red/util_log
*/
addHandler: function(func) {
logHandlers.push(func);
},
/**
* Remove a log handler function
* @memberof @node-red/util_log
*/
removeHandler: function(func) {
var index = logHandlers.indexOf(func);
if (index > -1) {
logHandlers.splice(index,1);
}
},
/**
* Log a message object
* @memberof @node-red/util_log
*/
log: function(msg) {
msg.timestamp = Date.now();
logHandlers.forEach(function(handler) {
handler.emit("log",msg);
});
},
/**
* Log a message at INFO level
* @memberof @node-red/util_log
*/
info: function(msg) {
log.log({level:log.INFO,msg:msg});
},
/**
* Log a message at WARN level
* @memberof @node-red/util_log
*/
warn: function(msg) {
log.log({level:log.WARN,msg:msg});
},
/**
* Log a message at ERROR level
* @memberof @node-red/util_log
*/
error: function(msg) {
log.log({level:log.ERROR,msg:msg});
},
/**
* Log a message at TRACE level
* @memberof @node-red/util_log
*/
trace: function(msg) {
log.log({level:log.TRACE,msg:msg});
},
/**
* Log a message at DEBUG level
* @memberof @node-red/util_log
*/
debug: function(msg) {
log.log({level:log.DEBUG,msg:msg});
},
/**
* Check if metrics are enabled
* @memberof @node-red/util_log
*/
metric: function() {
return metricsEnabled;
},
/**
* Log an audit event.
* @memberof @node-red/util_log
*/
audit: function(msg,req) {
msg.level = log.AUDIT;
if (req) {
msg.user = req.user;
msg.path = req.path;
msg.ip = req.ip || (req.headers && req.headers['x-forwarded-for']) || (req.connection && req.connection.remoteAddress) || undefined;
}
log.log(msg);
}
}
/**
* Perform a message catalog lookup.
* @name _
* @function
* @memberof @node-red/util_log
*/
log["_"] = i18n._;
File diff suppressed because it is too large Load Diff