@nr-connect/node-red 0.0.0-stage → 1.0.1

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.
@@ -0,0 +1,258 @@
1
+ <script type="text/javascript">
2
+ RED.nodes.registerType("nr-connect-notify", {
3
+ category: "network",
4
+ color: "#e6625d",
5
+ defaults: {
6
+ name: { value: "" },
7
+ title: { value: "Node-RED Alert" },
8
+ titleType: { value: "str" },
9
+ body: { value: "payload" },
10
+ bodyType: { value: "msg" },
11
+ pageId: { value: "" },
12
+ target: { value: "all" },
13
+ emails: {
14
+ value: "",
15
+ validate: function (v) {
16
+ var target = $("#node-input-target").length
17
+ ? $("#node-input-target").val()
18
+ : this.target || "all";
19
+ if (target !== "emails") return true;
20
+ return String(v || "")
21
+ .split(/[,;\n]+/)
22
+ .some(function (entry) {
23
+ return entry.trim().length > 0;
24
+ });
25
+ }
26
+ },
27
+ url: { value: "" },
28
+ tag: { value: "" },
29
+ urgency: { value: "normal" },
30
+ requireInteraction: { value: false }
31
+ },
32
+ inputs: 1,
33
+ outputs: 1,
34
+ icon: "font-awesome/fa-bell",
35
+ align: "right",
36
+ paletteLabel: "nrc notify",
37
+ label: function () {
38
+ return this.name || "nrc notify";
39
+ },
40
+ labelStyle: function () {
41
+ return this.name ? "node_label_italic" : "";
42
+ },
43
+ oneditprepare: function () {
44
+ var savedPageId = this.pageId || "";
45
+
46
+ $("#node-input-title").typedInput({
47
+ default: "str",
48
+ types: ["str", "msg", "flow", "global"],
49
+ typeField: "#node-input-titleType"
50
+ });
51
+
52
+ $("#node-input-body").typedInput({
53
+ default: "msg",
54
+ types: ["msg", "str", "flow", "global"],
55
+ typeField: "#node-input-bodyType"
56
+ });
57
+
58
+ function updateTargetVisibility() {
59
+ var target = $("#node-input-target").val();
60
+ var isEmails = target === "emails";
61
+ $("#node-row-emails").toggle(isEmails);
62
+ if (!isEmails) {
63
+ $("#node-input-emails").toggleClass("input-error", false);
64
+ } else {
65
+ var hasEmail = String($("#node-input-emails").val() || "")
66
+ .split(/[,;\n]+/)
67
+ .some(function (entry) {
68
+ return entry.trim().length > 0;
69
+ });
70
+ $("#node-input-emails").toggleClass("input-error", !hasEmail);
71
+ }
72
+ }
73
+ $("#node-input-target").on("change", updateTargetVisibility);
74
+ $("#node-input-emails")
75
+ .on("input", updateTargetVisibility)
76
+ .on("change", updateTargetVisibility);
77
+ updateTargetVisibility();
78
+
79
+ var hasAdvancedValues = Boolean(
80
+ (this.url && String(this.url).trim()) ||
81
+ (this.tag && String(this.tag).trim()) ||
82
+ (this.urgency && this.urgency !== "normal") ||
83
+ this.requireInteraction
84
+ );
85
+ var advancedExpanded = hasAdvancedValues;
86
+
87
+ function updateAdvancedSection() {
88
+ $("#node-notify-advanced-section").toggle(advancedExpanded);
89
+ $("#node-notify-advanced-icon")
90
+ .toggleClass("fa-caret-down", advancedExpanded)
91
+ .toggleClass("fa-caret-right", !advancedExpanded);
92
+ $("#node-notify-advanced-toggle").attr(
93
+ "aria-expanded",
94
+ advancedExpanded ? "true" : "false"
95
+ );
96
+ }
97
+
98
+ $("#node-notify-advanced-toggle").on("click", function (e) {
99
+ if (e && typeof e.preventDefault === "function") e.preventDefault();
100
+ advancedExpanded = !advancedExpanded;
101
+ updateAdvancedSection();
102
+ });
103
+ updateAdvancedSection();
104
+
105
+ var $pageSelect = $("#node-input-pageId");
106
+ var $pageHint = $("#node-notify-page-hint");
107
+ $.getJSON("nr-connect/status")
108
+ .done(function (status) {
109
+ $pageSelect.empty();
110
+ $pageSelect.append(
111
+ $("<option></option>").val("").text("Any page (no page restriction)")
112
+ );
113
+ var pages = Array.isArray(status && status.pages) ? status.pages : [];
114
+ var foundSaved = savedPageId === "";
115
+ var addedCount = 0;
116
+ pages.forEach(function (p) {
117
+ if (!p || !p.id) return;
118
+ if (p.id === savedPageId) foundSaved = true;
119
+ var label = (p.name || "Untitled Page") + " (" + (p.path || "/") + ")";
120
+ $pageSelect.append($("<option></option>").val(p.id).text(label));
121
+ addedCount += 1;
122
+ });
123
+ if (savedPageId && !foundSaved) {
124
+ $pageSelect.append(
125
+ $("<option></option>").val(savedPageId).text("Page ID: " + savedPageId)
126
+ );
127
+ }
128
+ $pageSelect.val(savedPageId);
129
+ if (addedCount > 0) {
130
+ $pageHint.text(
131
+ "Optional: restricts delivery to users who can view this page and opens it on click."
132
+ );
133
+ } else {
134
+ $pageHint.text(
135
+ "No Dashboard 2.0 pages synced yet. Deploy a Dashboard 2.0 page to scope alerts by page."
136
+ );
137
+ }
138
+ })
139
+ .fail(function () {
140
+ if (savedPageId && $pageSelect.find("option[value='" + savedPageId + "']").length === 0) {
141
+ $pageSelect.append(
142
+ $("<option></option>").val(savedPageId).text("Page ID: " + savedPageId)
143
+ );
144
+ }
145
+ $pageSelect.val(savedPageId);
146
+ $pageHint.text(
147
+ "Could not load Dashboard 2.0 pages (NR Connect may be offline)."
148
+ );
149
+ });
150
+ }
151
+ });
152
+ </script>
153
+
154
+ <script type="text/html" data-template-name="nr-connect-notify">
155
+ <div class="form-row">
156
+ <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
157
+ <input type="text" id="node-input-name" placeholder="Name" />
158
+ </div>
159
+ <div class="form-row">
160
+ <label for="node-input-title"><i class="fa fa-header"></i> Title</label>
161
+ <input type="text" id="node-input-title" placeholder="Node-RED Alert (or msg.topic)" />
162
+ <input type="hidden" id="node-input-titleType" />
163
+ </div>
164
+ <div class="form-row">
165
+ <label for="node-input-body"><i class="fa fa-comment"></i> Body</label>
166
+ <input type="text" id="node-input-body" placeholder="Notification message" />
167
+ <input type="hidden" id="node-input-bodyType" />
168
+ </div>
169
+ <div class="form-row">
170
+ <label for="node-input-target"><i class="fa fa-users"></i> Recipients</label>
171
+ <select id="node-input-target" style="width: 70%;">
172
+ <option value="all">All instance members</option>
173
+ <option value="admins">Admins &amp; owner only</option>
174
+ <option value="emails">Specific emails</option>
175
+ </select>
176
+ </div>
177
+ <div class="form-row" id="node-row-emails">
178
+ <label for="node-input-emails"><i class="fa fa-envelope"></i> Emails</label>
179
+ <input type="text" id="node-input-emails" placeholder="alice@example.com, bob@example.com" />
180
+ <div style="margin-left: 105px; margin-top: 4px; font-size: 0.85em; opacity: 0.8;">
181
+ Separate multiple addresses with commas or semicolons.
182
+ </div>
183
+ </div>
184
+ <div class="form-row">
185
+ <label for="node-input-pageId"><i class="fa fa-window-maximize"></i> Page Scope</label>
186
+ <select id="node-input-pageId" style="width: 70%;">
187
+ <option value="">Any page (no page restriction)</option>
188
+ </select>
189
+ <div id="node-notify-page-hint" style="margin-left: 105px; margin-top: 4px; font-size: 0.85em; opacity: 0.8;">
190
+ Optional: restricts delivery to users who can view this page and opens it on click.
191
+ </div>
192
+ </div>
193
+
194
+ <div class="form-row" style="margin-top: 12px; border-top: 1px solid var(--red-ui-secondary-border-color, #ddd); padding-top: 8px;">
195
+ <a href="#" id="node-notify-advanced-toggle" aria-expanded="false" style="text-decoration: none; font-weight: 600;">
196
+ <i id="node-notify-advanced-icon" class="fa fa-caret-right" style="width: 12px;"></i>
197
+ Advanced options
198
+ </a>
199
+ </div>
200
+ <div id="node-notify-advanced-section" style="display: none;">
201
+ <div class="form-row">
202
+ <label for="node-input-url"><i class="fa fa-link"></i> Click URL</label>
203
+ <input type="text" id="node-input-url" placeholder="/dashboard/hvac (defaults to Page Scope)" />
204
+ <div style="margin-left: 105px; margin-top: 4px; font-size: 0.85em; opacity: 0.8;">
205
+ Dashboard path to open when the notification is clicked.
206
+ </div>
207
+ </div>
208
+ <div class="form-row">
209
+ <label for="node-input-tag"><i class="fa fa-bookmark"></i> Replace Tag</label>
210
+ <input type="text" id="node-input-tag" placeholder="e.g. hvac-alarm (optional)" />
211
+ <div style="margin-left: 105px; margin-top: 4px; font-size: 0.85em; opacity: 0.8;">
212
+ New alerts with the same tag replace older unread alerts instead of stacking.
213
+ </div>
214
+ </div>
215
+ <div class="form-row">
216
+ <label for="node-input-urgency"><i class="fa fa-bolt"></i> Urgency</label>
217
+ <select id="node-input-urgency" style="width: 70%;">
218
+ <option value="normal">Normal (default)</option>
219
+ <option value="high">High (deliver immediately)</option>
220
+ <option value="low">Low (battery-friendly)</option>
221
+ <option value="very-low">Very Low (background only)</option>
222
+ </select>
223
+ </div>
224
+ <div class="form-row">
225
+ <label>&nbsp;</label>
226
+ <input type="checkbox" id="node-input-requireInteraction" style="display:inline-block; width:auto; vertical-align:top;" />
227
+ <label for="node-input-requireInteraction" style="width:70%;">Require user click/dismissal</label>
228
+ <div style="margin-left: 105px; margin-top: 2px; font-size: 0.85em; opacity: 0.8;">
229
+ Keeps the notification on screen until dismissed (where supported by the browser/OS).
230
+ </div>
231
+ </div>
232
+ </div>
233
+ </script>
234
+
235
+ <script type="text/html" data-help-name="nr-connect-notify">
236
+ <p>Sends a browser push notification to subscribed Dashboard 2.0 users via NR Connect.</p>
237
+ <h3>Details</h3>
238
+ <p>Uses the active NR Connect connection from runtime settings—no push credentials or secrets are stored in <code>flows.json</code>. Users must enable push notifications via the <b>nrc profile</b> widget to receive alerts.</p>
239
+ <p><b>Recipients</b> and <b>Page Scope</b> both apply: a user must match the selected recipient group <i>and</i> have permission to view the chosen Dashboard 2.0 page (if set). Clicking the notification opens <b>Click URL</b>, or falls back to the selected <b>Page Scope</b>.</p>
240
+ <h3>Inputs</h3>
241
+ <dl class="message-properties">
242
+ <dt>payload <span class="property-type">string | object</span></dt>
243
+ <dd>Default notification body when <b>Body</b> is set to <code>msg.payload</code>. Objects are JSON-serialized.</dd>
244
+ <dt class="optional">topic <span class="property-type">string</span></dt>
245
+ <dd>Fallback notification title if the configured <b>Title</b> evaluates to empty.</dd>
246
+ <dt class="optional">pageId <span class="property-type">string</span></dt>
247
+ <dd>Overrides the configured <b>Page Scope</b> for this message.</dd>
248
+ <dt class="optional">recipients <span class="property-type">string | string[]</span></dt>
249
+ <dd>Comma/semicolon-separated emails or array of emails. Automatically targets those emails unless <code>msg.notification.target</code> is explicitly set.</dd>
250
+ <dt class="optional">notification <span class="property-type">object</span></dt>
251
+ <dd>Per-message overrides (highest priority): <code>{ title, body, pageId, url, tag, icon, image, target, emails, recipients, requireInteraction, urgency, ttlSeconds, data }</code>.</dd>
252
+ </dl>
253
+ <h3>Outputs</h3>
254
+ <dl class="message-properties">
255
+ <dt>pushResult <span class="property-type">object</span></dt>
256
+ <dd>Delivery summary returned by the portal: <code>{ ok, sentCount, failedCount, removedCount, targetedUsersCount }</code>.</dd>
257
+ </dl>
258
+ </script>
@@ -0,0 +1,303 @@
1
+ "use strict";
2
+
3
+ const {
4
+ getActiveConfig,
5
+ onActiveConfigChange,
6
+ sendPushNotification,
7
+ } = require("../lib/pushAgent");
8
+
9
+ const STATUS_RESET_MS = 5000;
10
+ const MAX_TTL_SECONDS = 2_419_200;
11
+
12
+ function sanitizeExtraData(raw) {
13
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
14
+ const sanitized = {};
15
+ let hasKeys = false;
16
+ for (const [key, value] of Object.entries(raw)) {
17
+ if (value === undefined || value === null) continue;
18
+ const safeKey = String(key).slice(0, 200);
19
+ if (!safeKey) continue;
20
+ if (
21
+ typeof value === "string" ||
22
+ typeof value === "number" ||
23
+ typeof value === "boolean"
24
+ ) {
25
+ if (typeof value === "number" && !Number.isFinite(value)) continue;
26
+ sanitized[safeKey] = value;
27
+ hasKeys = true;
28
+ } else {
29
+ try {
30
+ sanitized[safeKey] = JSON.stringify(value);
31
+ hasKeys = true;
32
+ } catch {
33
+ // Skip unserializable values
34
+ }
35
+ }
36
+ }
37
+ return hasKeys ? sanitized : null;
38
+ }
39
+
40
+ function evaluatePropertyAsync(RED, value, type, node, msg) {
41
+ if (!type || type === "str") {
42
+ return Promise.resolve(value ?? "");
43
+ }
44
+ return new Promise((resolve, reject) => {
45
+ RED.util.evaluateNodeProperty(value, type, node, msg, (err, result) => {
46
+ if (err) reject(err);
47
+ else resolve(result);
48
+ });
49
+ });
50
+ }
51
+
52
+ function normalizeStringOrNull(val) {
53
+ if (typeof val !== "string") return null;
54
+ const trimmed = val.trim();
55
+ return trimmed ? trimmed : null;
56
+ }
57
+
58
+ function parseEmailsList(raw) {
59
+ if (Array.isArray(raw)) {
60
+ return Array.from(
61
+ new Set(raw.map((e) => String(e || "").trim().toLowerCase()).filter(Boolean))
62
+ );
63
+ }
64
+ if (typeof raw === "string") {
65
+ return Array.from(
66
+ new Set(
67
+ raw
68
+ .split(/[,;\n]+/)
69
+ .map((e) => e.trim().toLowerCase())
70
+ .filter(Boolean)
71
+ )
72
+ );
73
+ }
74
+ return [];
75
+ }
76
+
77
+ async function buildNotificationPayload(RED, node, config, msg) {
78
+ const override =
79
+ msg && typeof msg.notification === "object" && msg.notification !== null
80
+ ? msg.notification
81
+ : {};
82
+
83
+ const evaluatedTitle = await evaluatePropertyAsync(
84
+ RED,
85
+ config.title,
86
+ config.titleType || "str",
87
+ node,
88
+ msg
89
+ );
90
+ const evaluatedBody = await evaluatePropertyAsync(
91
+ RED,
92
+ config.body || "payload",
93
+ config.bodyType || "msg",
94
+ node,
95
+ msg
96
+ );
97
+
98
+ const rawTitle =
99
+ override.title ??
100
+ (normalizeStringOrNull(String(evaluatedTitle ?? "")) ||
101
+ normalizeStringOrNull(msg?.topic) ||
102
+ "Node-RED Alert");
103
+ const title = String(rawTitle).trim() || "Node-RED Alert";
104
+
105
+ let bodyStr = "";
106
+ const rawBody = override.body ?? evaluatedBody;
107
+ if (rawBody !== undefined && rawBody !== null) {
108
+ bodyStr =
109
+ typeof rawBody === "string"
110
+ ? rawBody.trim()
111
+ : JSON.stringify(rawBody);
112
+ }
113
+ if (!bodyStr) {
114
+ throw new Error("Notification body cannot be empty");
115
+ }
116
+
117
+ const pageId = normalizeStringOrNull(override.pageId ?? msg?.pageId ?? config.pageId);
118
+ const url = normalizeStringOrNull(override.url ?? config.url);
119
+ const tag = normalizeStringOrNull(override.tag ?? config.tag);
120
+ const icon = normalizeStringOrNull(override.icon ?? config.icon);
121
+ const image = normalizeStringOrNull(override.image ?? config.image);
122
+
123
+ const recipientOverride = override.emails ?? override.recipients ?? msg?.recipients;
124
+ const parsedEmails = recipientOverride
125
+ ? parseEmailsList(recipientOverride)
126
+ : parseEmailsList(config.emails);
127
+
128
+ let target = override.target || config.target || "all";
129
+ if (recipientOverride && parsedEmails.length > 0 && !override.target) {
130
+ target = "emails";
131
+ }
132
+
133
+ const requireInteraction =
134
+ typeof override.requireInteraction === "boolean"
135
+ ? override.requireInteraction
136
+ : Boolean(config.requireInteraction);
137
+
138
+ const urgency = override.urgency || config.urgency || "normal";
139
+
140
+ const payload = {
141
+ title: title.slice(0, 200),
142
+ body: bodyStr.slice(0, 2000),
143
+ target,
144
+ requireInteraction,
145
+ urgency,
146
+ };
147
+
148
+ if (pageId) payload.pageId = pageId;
149
+ if (url) payload.url = url;
150
+ if (tag) payload.tag = tag;
151
+ if (icon) payload.icon = icon;
152
+ if (image) payload.image = image;
153
+ if (target === "emails") payload.emails = parsedEmails;
154
+ if (
155
+ typeof override.ttlSeconds === "number" &&
156
+ Number.isFinite(override.ttlSeconds)
157
+ ) {
158
+ payload.ttlSeconds = Math.min(
159
+ MAX_TTL_SECONDS,
160
+ Math.max(0, Math.trunc(override.ttlSeconds))
161
+ );
162
+ }
163
+ const safeData = sanitizeExtraData(override.data);
164
+ if (safeData) {
165
+ payload.data = safeData;
166
+ }
167
+
168
+ return payload;
169
+ }
170
+
171
+ module.exports = function (RED) {
172
+ function NrConnectNotifyNode(config) {
173
+ RED.nodes.createNode(this, config);
174
+ const node = this;
175
+ let statusResetTimer = null;
176
+ let closed = false;
177
+ let inFlightCount = 0;
178
+
179
+ const clearStatusResetTimer = () => {
180
+ if (statusResetTimer) {
181
+ clearTimeout(statusResetTimer);
182
+ statusResetTimer = null;
183
+ }
184
+ };
185
+
186
+ const refreshConnectionStatus = () => {
187
+ if (closed || inFlightCount > 0) return;
188
+ const active = getActiveConfig();
189
+ if (!active || !active.rawToken) {
190
+ node.status({ fill: "yellow", shape: "ring", text: "not connected" });
191
+ } else {
192
+ node.status({ fill: "blue", shape: "dot", text: "ready" });
193
+ }
194
+ };
195
+
196
+ const scheduleStatusReset = () => {
197
+ clearStatusResetTimer();
198
+ if (closed) return;
199
+ statusResetTimer = setTimeout(() => {
200
+ statusResetTimer = null;
201
+ refreshConnectionStatus();
202
+ }, STATUS_RESET_MS);
203
+ if (typeof statusResetTimer.unref === "function") {
204
+ statusResetTimer.unref();
205
+ }
206
+ };
207
+
208
+ refreshConnectionStatus();
209
+ const unsubscribeConfigChange = onActiveConfigChange(() => {
210
+ if (!statusResetTimer && inFlightCount === 0) {
211
+ refreshConnectionStatus();
212
+ }
213
+ });
214
+
215
+ node.on("close", () => {
216
+ closed = true;
217
+ clearStatusResetTimer();
218
+ unsubscribeConfigChange();
219
+ });
220
+
221
+ node.on("input", async (msg, send, done) => {
222
+ clearStatusResetTimer();
223
+ const activeConfig = getActiveConfig();
224
+ if (!activeConfig || !activeConfig.rawToken || !activeConfig.apiUrl) {
225
+ const err = new Error("NR Connect is not connected to the portal");
226
+ if (!closed) {
227
+ node.status({ fill: "red", shape: "ring", text: "not connected" });
228
+ scheduleStatusReset();
229
+ }
230
+ if (done) done(err);
231
+ else node.error(err, msg);
232
+ return;
233
+ }
234
+
235
+ inFlightCount += 1;
236
+ try {
237
+ if (!closed) {
238
+ node.status({ fill: "blue", shape: "ring", text: "sending..." });
239
+ }
240
+ const payload = await buildNotificationPayload(RED, node, config, msg);
241
+
242
+ if (payload.target === "emails" && (!payload.emails || payload.emails.length === 0)) {
243
+ const emptyResult = {
244
+ ok: true,
245
+ sentCount: 0,
246
+ failedCount: 0,
247
+ removedCount: 0,
248
+ targetedUsersCount: 0,
249
+ };
250
+ inFlightCount = Math.max(0, inFlightCount - 1);
251
+ if (!closed && inFlightCount === 0) {
252
+ node.status({ fill: "yellow", shape: "ring", text: "no recipient emails" });
253
+ scheduleStatusReset();
254
+ }
255
+ send({ ...msg, pushResult: emptyResult });
256
+ if (done) done();
257
+ return;
258
+ }
259
+
260
+ const result = await sendPushNotification(activeConfig, payload);
261
+ inFlightCount = Math.max(0, inFlightCount - 1);
262
+
263
+ const sentCount = Number(result?.sentCount || 0);
264
+ if (!closed && inFlightCount === 0) {
265
+ if (sentCount > 0) {
266
+ node.status({
267
+ fill: "green",
268
+ shape: "dot",
269
+ text: `sent (${sentCount} device${sentCount === 1 ? "" : "s"})`,
270
+ });
271
+ } else {
272
+ node.status({
273
+ fill: "yellow",
274
+ shape: "ring",
275
+ text: "0 active devices",
276
+ });
277
+ }
278
+ scheduleStatusReset();
279
+ }
280
+
281
+ const outMsg = { ...msg, pushResult: result };
282
+ send(outMsg);
283
+ if (done) done();
284
+ } catch (err) {
285
+ inFlightCount = Math.max(0, inFlightCount - 1);
286
+ if (!closed && inFlightCount === 0) {
287
+ node.status({
288
+ fill: "red",
289
+ shape: "ring",
290
+ text: (err?.message || "send failed").slice(0, 32),
291
+ });
292
+ scheduleStatusReset();
293
+ }
294
+ if (done) done(err);
295
+ else node.error(err, msg);
296
+ }
297
+ });
298
+ }
299
+
300
+ RED.nodes.registerType("nr-connect-notify", NrConnectNotifyNode);
301
+ };
302
+
303
+ module.exports.buildNotificationPayload = buildNotificationPayload;