@theotherwillembotha/node-red-whatsapp 0.0.55 → 0.3.0

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/build/index.js CHANGED
@@ -18,4 +18,5 @@ __exportStar(require("./whatsapp/service/WhatsappService"), exports);
18
18
  __exportStar(require("./whatsapp/node/WhatsappAccountConfigNode"), exports);
19
19
  __exportStar(require("./whatsapp/node/WhatsappGroupConfigNode"), exports);
20
20
  __exportStar(require("./whatsapp/node/WhatsappSendMessageNode"), exports);
21
+ __exportStar(require("./whatsapp/node/WhatsappDynamicSendMessageNode"), exports);
21
22
  __exportStar(require("./whatsapp/node/WhatsappReceiveMessageNode"), exports);
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ /**
3
+ * NodeManagerRuntime.ts
4
+ *
5
+ * STANDALONE - zero imports from the rest of plugincore.
6
+ *
7
+ * This file is compiled and copied into every plugin's build output so that
8
+ * plugins are self-contained and do not require plugincore to be separately
9
+ * installed in the user's Node-RED environment.
10
+ *
11
+ * When multiple plugins are deployed, each ships its own copy of this file.
12
+ * The first plugin to load registers its NodeManager and nodes; subsequent
13
+ * copies operate independently on their own node types with no conflict.
14
+ *
15
+ * POST_CONSTRUCT_KEY is intentionally a plain string (not a Symbol) so that
16
+ * the decorators (from plugincore's NodeConstructor, loaded via the plugin's
17
+ * dependency on plugincore) and this runtime file (a separate module instance)
18
+ * resolve to the same property key on node instances.
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.NodeManager = exports.POST_CONSTRUCT_KEY = exports.NODEMANAGER_API_VERSION = void 0;
22
+ exports.runPostConstructInitializers = runPostConstructInitializers;
23
+ // ─── API version ────────────────────────────────────────────────────────────
24
+ // Semver of the NodeManager API contract - independent of plugincore's package
25
+ // version. Bump when the contract changes; plugins can read this to warn users
26
+ // that they were built against a different NodeManager version.
27
+ exports.NODEMANAGER_API_VERSION = "1.0.0";
28
+ // ─── Shared key for post-construct initializer lists ────────────────────────
29
+ // Must be a plain string so it resolves identically across module instances.
30
+ exports.POST_CONSTRUCT_KEY = '__plugincore_postConstructInitializers__';
31
+ // ─── Post-construct initializer runner ───────────────────────────────────────
32
+ function runPostConstructInitializers(instance) {
33
+ const initializers = instance[exports.POST_CONSTRUCT_KEY];
34
+ if (!initializers || initializers.length === 0)
35
+ return;
36
+ const className = instance.constructor.name;
37
+ initializers.forEach((init, index) => {
38
+ try {
39
+ init(instance);
40
+ }
41
+ catch (error) {
42
+ console.error(`Post-construct initialization failed:\n` +
43
+ ` Class: ${className}\n` +
44
+ ` Initializer: ${index + 1}/${initializers.length}\n` +
45
+ ` Error: ${error instanceof Error ? error.message : String(error)}`);
46
+ throw error;
47
+ }
48
+ });
49
+ delete instance[exports.POST_CONSTRUCT_KEY];
50
+ }
51
+ // ─── NodeManager ─────────────────────────────────────────────────────────────
52
+ // RED is stored on `global` rather than as a static class field so that all
53
+ // module instances of NodeManagerRuntime (the local copy bundled into Nodes.js
54
+ // and the copy bundled via plugincore's NodeConstructor) share the same value.
55
+ // Without this, esbuild's two separate inline copies would have independent
56
+ // static fields and the one used by decorators would never see RED being set.
57
+ const _GLOBAL_RED_KEY = '__plugincore_NodeManager_RED__';
58
+ // ─── Global node-type registration guard ─────────────────────────────────────
59
+ // When multiple self-contained plugins are installed they each bundle plugincore
60
+ // inline and each try to call RED.nodes.registerType for the same shared
61
+ // infrastructure node types (ConsoleLoggerConfigNode, RestLoggerConfigNode, etc.).
62
+ // Node-RED rejects duplicate registrations with a warning and the second
63
+ // plugin's Nodes.js fails to load. This global set tracks which types have
64
+ // already been registered so subsequent plugins silently skip them.
65
+ const _GLOBAL_REGISTERED_NODES_KEY = '__plugincore_registered_nodes__';
66
+ function getRegisteredNodes() {
67
+ if (!global[_GLOBAL_REGISTERED_NODES_KEY]) {
68
+ global[_GLOBAL_REGISTERED_NODES_KEY] = new Set();
69
+ }
70
+ return global[_GLOBAL_REGISTERED_NODES_KEY];
71
+ }
72
+ class NodeManager {
73
+ constructor(RED) {
74
+ this.typeBacklog = [];
75
+ global[_GLOBAL_RED_KEY] = RED;
76
+ const nodeTypeServiceId = "@theotherwillembotha/nodetypeservice";
77
+ const nodeTypeServiceListener = (pluginID) => {
78
+ if (pluginID === nodeTypeServiceId) {
79
+ RED.events.off('plugin.instantiated', nodeTypeServiceListener);
80
+ this.nodeTypeService = RED.plugins.get(nodeTypeServiceId).instance;
81
+ for (const nodeType of this.typeBacklog) {
82
+ for (const tag of nodeType.getNodeDescriptor().tags()) {
83
+ this.nodeTypeService.registerNodeType(tag, nodeType);
84
+ }
85
+ }
86
+ this.typeBacklog = [];
87
+ }
88
+ };
89
+ this.nodeTypeService = RED.plugins.get(nodeTypeServiceId)?.instance;
90
+ if (!this.nodeTypeService) {
91
+ RED.events.on('plugin.instantiated', nodeTypeServiceListener);
92
+ }
93
+ }
94
+ static get RED() {
95
+ return global[_GLOBAL_RED_KEY];
96
+ }
97
+ registerNodeType(typeName, type) {
98
+ if (!type) {
99
+ console.error(`[NodeManager v${exports.NODEMANAGER_API_VERSION}] Type "${typeName}" is undefined. ` +
100
+ `Ensure it is exported and included in GenerateNodes.`);
101
+ return this;
102
+ }
103
+ const registeredNodes = getRegisteredNodes();
104
+ if (registeredNodes.has(typeName)) {
105
+ // Already registered by another plugin - skip to avoid Node-RED duplicate-registration error.
106
+ return this;
107
+ }
108
+ registeredNodes.add(typeName);
109
+ const nodeConstructor = function (config) {
110
+ try {
111
+ NodeManager.RED.nodes.createNode(this, config);
112
+ const node = new type(this, config);
113
+ runPostConstructInitializers(node);
114
+ if (node.onInit) {
115
+ node.onInit();
116
+ }
117
+ }
118
+ catch (error) {
119
+ console.error(`[NodeManager v${exports.NODEMANAGER_API_VERSION}] Failed to construct node "${typeName}":`, error);
120
+ }
121
+ };
122
+ try {
123
+ NodeManager.RED.nodes.registerType(typeName, nodeConstructor, { settings: {} });
124
+ const nodeDescription = type.getNodeDescriptor();
125
+ if (this.nodeTypeService) {
126
+ for (const tag of nodeDescription.tags()) {
127
+ this.nodeTypeService.registerNodeType(tag, type);
128
+ }
129
+ }
130
+ else {
131
+ this.typeBacklog.push(type);
132
+ }
133
+ }
134
+ catch (error) {
135
+ console.error(`[NodeManager v${exports.NODEMANAGER_API_VERSION}] Failed to register node type "${typeName}":`, error);
136
+ }
137
+ return this;
138
+ }
139
+ }
140
+ exports.NodeManager = NodeManager;
@@ -19,7 +19,12 @@ let WhatsappAccountConfigNode = class WhatsappAccountConfigNode extends node_red
19
19
  this.client = WhatsappService_1.WhatsappService.getClient(config.localConnectionId);
20
20
  }
21
21
  getGroup(groupId) {
22
- return this.client ? this.client.getGroupClient(groupId) : undefined;
22
+ const client = WhatsappService_1.WhatsappService.getClient(this.config().localConnectionId);
23
+ return client ? client.getGroupClient(groupId) : undefined;
24
+ }
25
+ async sendMessage(chatId, message) {
26
+ const resolvedJid = await this.client.resolveJid(chatId);
27
+ await this.client.sendMessage(resolvedJid, message);
23
28
  }
24
29
  };
25
30
  exports.WhatsappAccountConfigNode = WhatsappAccountConfigNode;
@@ -29,7 +34,7 @@ exports.WhatsappAccountConfigNode = WhatsappAccountConfigNode = __decorate([
29
34
  name: "Whatsapp Config Node",
30
35
  group: "config",
31
36
  sourceFile: node_red_plugincore_1.SourceUtility.getSourcePath("/build/", "/src/") + "WhatsappAccountConfigNode.html",
32
- package: "@theotherwillembotha/nodered_whatsapp",
37
+ package: "@theotherwillembotha/node-red-whatsapp",
33
38
  tags: ["Whatsapp"]
34
39
  }),
35
40
  __metadata("design:paramtypes", [Object, Object])
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.WhatsappDynamicSendMessageNode = void 0;
16
+ const node_red_plugincore_1 = require("@theotherwillembotha/node-red-plugincore");
17
+ const node_red_plugincore_2 = require("@theotherwillembotha/node-red-plugincore");
18
+ const node_red_plugincore_3 = require("@theotherwillembotha/node-red-plugincore");
19
+ const handlebars_1 = __importDefault(require("handlebars"));
20
+ let WhatsappDynamicSendMessageNode = class WhatsappDynamicSendMessageNode extends node_red_plugincore_1.BaseNode {
21
+ constructor(node, config) {
22
+ super(node, config);
23
+ this.accountNode = node_red_plugincore_1.NodeManager.RED.nodes.getNode(config.accountConfig).node();
24
+ }
25
+ resolveField(value, valueType, message) {
26
+ switch (valueType) {
27
+ case "str": return handlebars_1.default.compile(value)({ msg: message });
28
+ case "msg": return value.split(".").reduce((obj, key) => obj?.[key], message);
29
+ case "flow": return this.node().context().flow.get(value);
30
+ case "global": return this.node().context().global.get(value);
31
+ default: return undefined;
32
+ }
33
+ }
34
+ async onMessageReceived(message) {
35
+ this.counter.inc();
36
+ const chatId = this.resolveField(this.config().recipient, this.config().recipientType, message);
37
+ if (!chatId) {
38
+ this.log.log({ error: "recipient resolved to empty value — message not sent" });
39
+ return;
40
+ }
41
+ let actions = [];
42
+ try {
43
+ actions = JSON.parse(this.config().payloads || "[]");
44
+ }
45
+ catch (e) { }
46
+ for (const action of actions) {
47
+ const resolved = this.resolveField(action.value, action.valueType, message);
48
+ let payload = {};
49
+ switch (action.type) {
50
+ case "text":
51
+ payload.text = resolved != null ? String(resolved) : undefined;
52
+ break;
53
+ case "image":
54
+ payload.image = resolved;
55
+ break;
56
+ case "video":
57
+ payload.video = resolved;
58
+ break;
59
+ case "document":
60
+ payload.document = resolved;
61
+ if (action.documentName) {
62
+ payload.documentName = String(this.resolveField(action.documentName, action.documentNameType ?? "str", message) ?? "");
63
+ }
64
+ if (action.documentMimetype) {
65
+ payload.documentMimetype = String(this.resolveField(action.documentMimetype, action.documentMimetypeType ?? "str", message) ?? "");
66
+ }
67
+ break;
68
+ }
69
+ let logPayload = { chatId: String(chatId) };
70
+ if (payload.text)
71
+ logPayload.text = payload.text;
72
+ if (payload.image)
73
+ logPayload.image = payload.image?.length;
74
+ if (payload.video)
75
+ logPayload.video = payload.video?.length;
76
+ if (payload.document)
77
+ logPayload.document = payload.document?.length;
78
+ this.log.log(logPayload);
79
+ await this.accountNode.sendMessage(String(chatId), payload);
80
+ }
81
+ }
82
+ };
83
+ exports.WhatsappDynamicSendMessageNode = WhatsappDynamicSendMessageNode;
84
+ __decorate([
85
+ (0, node_red_plugincore_3.Logger)(),
86
+ __metadata("design:type", node_red_plugincore_3.Log)
87
+ ], WhatsappDynamicSendMessageNode.prototype, "log", void 0);
88
+ __decorate([
89
+ (0, node_red_plugincore_2.Metrics)({ name: "counter", type: node_red_plugincore_2.MetricType.Counter, description: "number of messages sent" }),
90
+ __metadata("design:type", Object)
91
+ ], WhatsappDynamicSendMessageNode.prototype, "counter", void 0);
92
+ __decorate([
93
+ (0, node_red_plugincore_1.onInput)(),
94
+ __metadata("design:type", Function),
95
+ __metadata("design:paramtypes", [Object]),
96
+ __metadata("design:returntype", Promise)
97
+ ], WhatsappDynamicSendMessageNode.prototype, "onMessageReceived", null);
98
+ exports.WhatsappDynamicSendMessageNode = WhatsappDynamicSendMessageNode = __decorate([
99
+ (0, node_red_plugincore_1.NodeDescription)({
100
+ id: "WhatsappDynamicSendMessageNode",
101
+ name: "Whatsapp Dynamic Send Message Node",
102
+ group: "whatsapp",
103
+ sourceFile: node_red_plugincore_1.SourceUtility.getSourcePath("/build/", "/src/") + "WhatsappDynamicSendMessageNode.html",
104
+ package: "@theotherwillembotha/node-red-whatsapp",
105
+ templates: [
106
+ { template: node_red_plugincore_3.LoggerTemplate, config: {} },
107
+ { template: node_red_plugincore_2.MetricsTemplate, config: {} },
108
+ ],
109
+ tags: ["Whatsapp"]
110
+ }),
111
+ __metadata("design:paramtypes", [Object, Object])
112
+ ], WhatsappDynamicSendMessageNode);
@@ -15,20 +15,31 @@ let WhatsappGroupConfigNode = class WhatsappGroupConfigNode extends node_red_plu
15
15
  constructor(node, config) {
16
16
  super(node, config);
17
17
  this.accountconfigNode = node_red_plugincore_1.NodeManager.RED.nodes.getNode(config.accountConfig).node();
18
- this.group = this.accountconfigNode.getGroup(config.groupId);
18
+ }
19
+ getGroup() {
20
+ return this.accountconfigNode.getGroup(this.config().groupId);
19
21
  }
20
22
  send(message) {
21
- console.log("Sending message to ", this.group.id());
22
- this.group.sendMessage(message);
23
+ const group = this.getGroup();
24
+ if (!group) {
25
+ throw new Error(`WhatsappGroupConfigNode: group client not available — is the account linked and connected?`);
26
+ }
27
+ group.sendMessage(message);
23
28
  }
24
29
  subscribe(subscription) {
25
- this.group.subscribe(subscription);
30
+ const group = this.getGroup();
31
+ if (!group) {
32
+ throw new Error(`WhatsappGroupConfigNode: group client not available — is the account linked and connected?`);
33
+ }
34
+ group.subscribe(subscription);
26
35
  return subscription;
27
36
  }
28
37
  unsubscribe(subscription) {
29
- console.log("unsubscribing from", this.group.id());
30
- this.group.unsubscribe(subscription);
31
- return;
38
+ const group = this.getGroup();
39
+ if (!group)
40
+ return;
41
+ console.log("unsubscribing from", group.id());
42
+ group.unsubscribe(subscription);
32
43
  }
33
44
  };
34
45
  exports.WhatsappGroupConfigNode = WhatsappGroupConfigNode;
@@ -38,7 +49,7 @@ exports.WhatsappGroupConfigNode = WhatsappGroupConfigNode = __decorate([
38
49
  name: "Whatsapp Group Config Node",
39
50
  group: "config",
40
51
  sourceFile: node_red_plugincore_1.SourceUtility.getSourcePath("/build/", "/src/") + "WhatsappGroupConfigNode.html",
41
- package: "@theotherwillembotha/nodered_whatsapp",
52
+ package: "@theotherwillembotha/node-red-whatsapp",
42
53
  tags: ["Whatsapp"]
43
54
  }),
44
55
  __metadata("design:paramtypes", [Object, Object])
@@ -63,7 +63,7 @@ __decorate([
63
63
  ], WhatsappReceiveMessageNode.prototype, "log", void 0);
64
64
  __decorate([
65
65
  (0, node_red_plugincore_2.Metrics)({ name: "counter", type: node_red_plugincore_2.MetricType.Counter, description: "number of messages received" }),
66
- __metadata("design:type", node_red_plugincore_2.CounterMetric)
66
+ __metadata("design:type", Object)
67
67
  ], WhatsappReceiveMessageNode.prototype, "counter", void 0);
68
68
  exports.WhatsappReceiveMessageNode = WhatsappReceiveMessageNode = __decorate([
69
69
  (0, node_red_plugincore_1.NodeDescription)({
@@ -71,7 +71,7 @@ exports.WhatsappReceiveMessageNode = WhatsappReceiveMessageNode = __decorate([
71
71
  name: "Whatsapp Receive Message Node",
72
72
  group: "whatsapp",
73
73
  sourceFile: node_red_plugincore_1.SourceUtility.getSourcePath("/build/", "/src/") + "WhatsappReceiveMessageNode.html",
74
- package: "@theotherwillembotha/nodered_whatsapp",
74
+ package: "@theotherwillembotha/node-red-whatsapp",
75
75
  templates: [
76
76
  { template: node_red_plugincore_3.LoggerTemplate, config: {} },
77
77
  { template: node_red_plugincore_2.MetricsTemplate, config: {} },
@@ -22,45 +22,67 @@ let WhatsappSendMessageNode = class WhatsappSendMessageNode extends node_red_plu
22
22
  super(node, config);
23
23
  this.groupNode = node_red_plugincore_1.NodeManager.RED.nodes.getNode(config.groupConfig).node();
24
24
  }
25
- resolveValue(field, message) {
26
- switch (field.type) {
27
- case "str":
28
- return handlebars_1.default.compile(field.value)({ msg: message });
29
- case "msg":
30
- return field.value.split(".").reduce((obj, key) => obj?.[key], message);
31
- case "flow":
32
- return this.node().context().flow.get(field.value);
33
- case "global":
34
- return this.node().context().global.get(field.value);
35
- default:
36
- return undefined;
25
+ resolveField(value, valueType, message) {
26
+ switch (valueType) {
27
+ case "str": return handlebars_1.default.compile(value)({ msg: message });
28
+ case "msg": return value.split(".").reduce((obj, key) => obj?.[key], message);
29
+ case "flow": return this.node().context().flow.get(value);
30
+ case "global": return this.node().context().global.get(value);
31
+ default: return undefined;
37
32
  }
38
33
  }
39
34
  onMessageReceived(message) {
40
35
  this.counter.inc();
41
- let fields = [];
36
+ if (!this.groupNode) {
37
+ this.node().error("WhatsappSendMessageNode: no group config node found — check the node configuration.");
38
+ return;
39
+ }
40
+ let actions = [];
42
41
  try {
43
- fields = JSON.parse(this.config().payloads || "[]");
42
+ actions = JSON.parse(this.config().payloads || "[]");
44
43
  }
45
44
  catch (e) { }
46
- let payload = {};
47
- for (let field of fields) {
48
- if (!field.enabled)
49
- continue;
50
- let resolved = this.resolveValue(field, message);
51
- if (field.id === "text")
52
- payload.text = resolved != null ? String(resolved) : undefined;
53
- if (field.id === "image")
54
- payload.image = resolved;
45
+ for (const action of actions) {
46
+ const resolved = this.resolveField(action.value, action.valueType, message);
47
+ let payload = {};
48
+ switch (action.type) {
49
+ case "text":
50
+ payload.text = resolved != null ? String(resolved) : undefined;
51
+ break;
52
+ case "image":
53
+ payload.image = resolved;
54
+ break;
55
+ case "video":
56
+ payload.video = resolved;
57
+ break;
58
+ case "document":
59
+ payload.document = resolved;
60
+ if (action.documentName) {
61
+ payload.documentName = String(this.resolveField(action.documentName, action.documentNameType ?? "str", message) ?? "");
62
+ }
63
+ if (action.documentMimetype) {
64
+ payload.documentMimetype = String(this.resolveField(action.documentMimetype, action.documentMimetypeType ?? "str", message) ?? "");
65
+ }
66
+ break;
67
+ }
68
+ let logPayload = {};
69
+ if (payload.text)
70
+ logPayload.text = payload.text;
71
+ if (payload.image)
72
+ logPayload.image = payload.image?.length;
73
+ if (payload.video)
74
+ logPayload.video = payload.video?.length;
75
+ if (payload.document)
76
+ logPayload.document = payload.document?.length;
77
+ this.log.log(logPayload);
78
+ try {
79
+ this.groupNode.send(payload);
80
+ }
81
+ catch (e) {
82
+ this.node().error("WhatsappSendMessageNode: failed to send message — " + (e?.message ?? e), message);
83
+ return;
84
+ }
55
85
  }
56
- let logPayload = {};
57
- if (payload.text)
58
- logPayload.text = payload.text;
59
- if (payload.image)
60
- logPayload.image = payload.image?.length;
61
- this.log.log(logPayload);
62
- console.log(payload);
63
- this.groupNode.send(payload);
64
86
  }
65
87
  };
66
88
  exports.WhatsappSendMessageNode = WhatsappSendMessageNode;
@@ -70,7 +92,7 @@ __decorate([
70
92
  ], WhatsappSendMessageNode.prototype, "log", void 0);
71
93
  __decorate([
72
94
  (0, node_red_plugincore_2.Metrics)({ name: "counter", type: node_red_plugincore_2.MetricType.Counter, description: "number of messages sent" }),
73
- __metadata("design:type", node_red_plugincore_2.CounterMetric)
95
+ __metadata("design:type", Object)
74
96
  ], WhatsappSendMessageNode.prototype, "counter", void 0);
75
97
  __decorate([
76
98
  (0, node_red_plugincore_1.onInput)(),
@@ -84,7 +106,7 @@ exports.WhatsappSendMessageNode = WhatsappSendMessageNode = __decorate([
84
106
  name: "Whatsapp Send Message Node",
85
107
  group: "whatsapp",
86
108
  sourceFile: node_red_plugincore_1.SourceUtility.getSourcePath("/build/", "/src/") + "WhatsappSendMessageNode.html",
87
- package: "@theotherwillembotha/nodered_whatsapp",
109
+ package: "@theotherwillembotha/node-red-whatsapp",
88
110
  templates: [
89
111
  { template: node_red_plugincore_3.LoggerTemplate, config: {} },
90
112
  { template: node_red_plugincore_2.MetricsTemplate, config: {} },