fcm-v1-token 1.0.0 → 1.1.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/README.md +122 -5
- package/package.json +7 -3
- package/src/cli.js +447 -36
- package/src/index.d.ts +54 -0
- package/src/index.js +150 -0
package/README.md
CHANGED
|
@@ -35,12 +35,15 @@ The legacy FCM server key is **deprecated**. The modern **FCM HTTP v1 API** requ
|
|
|
35
35
|
- 🔁 **Caches the token ~1 hour and auto‑refreshes** it before expiry
|
|
36
36
|
- 📋 **Copies the token to your clipboard** automatically (and prints it copy‑friendly)
|
|
37
37
|
- 📤 **Sends push** via the FCM v1 API with a one‑line helper
|
|
38
|
+
- 📣 **Sends to a topic**: a notification (title, body, image), notification + custom data, data‑only, or your own custom JSON, delivered to every device subscribed to that topic on Android, iOS and web
|
|
39
|
+
- 👀 **Previews the exact FCM JSON** before sending, with a **dry‑run** option that validates without delivering
|
|
38
40
|
- 📦 **Zero config**, one dependency (`google-auth-library`), works with `npx`
|
|
39
41
|
|
|
40
42
|
## Table of contents
|
|
41
43
|
|
|
42
44
|
- [Install](#install)
|
|
43
45
|
- [Quick start (CLI)](#quick-start-cli)
|
|
46
|
+
- [Send a notification to a topic](#send-a-notification-to-a-topic)
|
|
44
47
|
- [CLI commands](#cli-commands)
|
|
45
48
|
- [Use as a library](#use-as-a-library)
|
|
46
49
|
- [How it works](#how-it-works)
|
|
@@ -107,12 +110,68 @@ curl -X POST \
|
|
|
107
110
|
|
|
108
111
|
---
|
|
109
112
|
|
|
113
|
+
## Send a notification to a topic
|
|
114
|
+
|
|
115
|
+
Pick **[3] Send a real notification to a topic** in the menu (or run `fcm-token topic`). Enter the topic, then choose what to send:
|
|
116
|
+
|
|
117
|
+
| Type | What the device gets |
|
|
118
|
+
| --- | --- |
|
|
119
|
+
| **Notification** | Title, body and an optional image, shown in the system tray |
|
|
120
|
+
| **Notification + data** | The same, plus your own `key=value` data for the app |
|
|
121
|
+
| **Data only** | A silent message that only your app's code receives |
|
|
122
|
+
| **Custom JSON** | Any FCM v1 message you paste. The topic you entered replaces any target in it |
|
|
123
|
+
|
|
124
|
+
You can also set the sound, the Android channel, the click action and the priority. Before anything is sent you see the exact FCM JSON and choose **Y** to send, **d** for a dry run that only validates it, or **n** to cancel.
|
|
125
|
+
|
|
126
|
+
```text
|
|
127
|
+
Topic : news
|
|
128
|
+
|
|
129
|
+
What do you want to send?
|
|
130
|
+
[1] Notification title, body, image — shows in the tray
|
|
131
|
+
[2] Notification + data the same, plus your own key/value data
|
|
132
|
+
[3] Data only silent — your app code handles it
|
|
133
|
+
[4] Custom JSON paste a full FCM v1 message
|
|
134
|
+
|
|
135
|
+
Title : Big Sale
|
|
136
|
+
Body : 50% off today
|
|
137
|
+
Image : https://example.com/sale.png
|
|
138
|
+
› screen=offers
|
|
139
|
+
› id=42
|
|
140
|
+
|
|
141
|
+
⚠ This goes to EVERY device subscribed to topic "news".
|
|
142
|
+
Send now? Y = send · d = dry run (validate only) · n = cancel
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Or send it in one line, without any prompts:
|
|
146
|
+
|
|
147
|
+
```bash
|
|
148
|
+
# Notification with an image and custom data
|
|
149
|
+
fcm-token send --topic news --title "Big Sale" --body "50% off today" \
|
|
150
|
+
--image https://example.com/sale.png --data screen=offers --data id=42
|
|
151
|
+
|
|
152
|
+
# Data-only (silent) message
|
|
153
|
+
fcm-token send --topic news --data-only --data type=sync --data count=3
|
|
154
|
+
|
|
155
|
+
# Your own FCM v1 message (JSON or a .json file)
|
|
156
|
+
fcm-token send --topic news --message ./message.json
|
|
157
|
+
|
|
158
|
+
# Validate with FCM without delivering anything
|
|
159
|
+
fcm-token send --topic news --title "Test" --dry-run
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
The same message works on **Android, iOS and web**. The image is set for Android and web (`notification.image`) and for iOS (`apns.fcm_options.image` with `mutable-content`). Data-only messages go out at high priority on Android and as background pushes on iOS.
|
|
163
|
+
|
|
164
|
+
> A topic message reaches **every** device subscribed to that topic in the project of your service account. FCM does not say how many devices that is. Use `--dry-run` while you are trying things out.
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
110
168
|
## CLI commands
|
|
111
169
|
|
|
112
170
|
```text
|
|
113
171
|
fcm-token Interactive menu (remembers your last account)
|
|
114
172
|
fcm-token token [source] Print an access token
|
|
115
|
-
fcm-token send [source] Send a
|
|
173
|
+
fcm-token send [source] Send a push to a device (interactive prompts)
|
|
174
|
+
fcm-token topic [source] Send a notification to a topic (interactive)
|
|
116
175
|
fcm-token use <source> Set / replace the saved service account
|
|
117
176
|
fcm-token whoami Show the saved service account
|
|
118
177
|
fcm-token forget Remove the saved service account
|
|
@@ -129,6 +188,26 @@ fcm-token --help Show help
|
|
|
129
188
|
| `--json` | Print full info (`token`, `projectId`, `expiresAt`) as JSON |
|
|
130
189
|
| `--no-copy` | Do not copy the token to the clipboard |
|
|
131
190
|
|
|
191
|
+
**Options for `send` / `topic`:** with any content option (`--title`, `--body`, `--image`, `--data`, `--data-only`, `--message`) the message is sent right away without prompts. Without them you get the interactive composer.
|
|
192
|
+
|
|
193
|
+
| Flag | Description |
|
|
194
|
+
| --- | --- |
|
|
195
|
+
| `--topic <name>` | Send to every device subscribed to this topic (`/topics/` prefix optional) |
|
|
196
|
+
| `--device <token>` | Send to one device registration token |
|
|
197
|
+
| `--title <text>` | Notification title |
|
|
198
|
+
| `--body <text>` | Notification body |
|
|
199
|
+
| `--image <url>` | Image URL (Android, iOS, web) |
|
|
200
|
+
| `--data <key=value>` | Custom data. Repeat it, or pass a JSON object |
|
|
201
|
+
| `--data-only` | Silent data message (no title/body/image) |
|
|
202
|
+
| `--message <json\|file>` | A full custom FCM v1 message |
|
|
203
|
+
| `--sound <name\|none>` | Notification sound (default `default`) |
|
|
204
|
+
| `--channel <id>` | Android notification channel id |
|
|
205
|
+
| `--click-action <name>` | Android `click_action` / iOS `category` |
|
|
206
|
+
| `--priority <high\|normal>` | Delivery priority (default `high`) |
|
|
207
|
+
| `--dry-run` | Validate with FCM only, deliver nothing |
|
|
208
|
+
| `--yes`, `-y` | Interactive mode: skip the confirm step |
|
|
209
|
+
| `--json` | Print the raw FCM response as JSON |
|
|
210
|
+
|
|
132
211
|
> Set `NO_COLOR=1` to disable colors. The short alias `fcmt` works everywhere, and `npx fcm-v1-token` runs the same tool without installing.
|
|
133
212
|
|
|
134
213
|
---
|
|
@@ -157,13 +236,39 @@ await sendPush('./service-account.json', {
|
|
|
157
236
|
});
|
|
158
237
|
```
|
|
159
238
|
|
|
160
|
-
Send to a **topic
|
|
239
|
+
Send to a **topic**. `sendToTopic` builds a message that works on Android, iOS and web:
|
|
161
240
|
|
|
162
241
|
```js
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
242
|
+
const { sendToTopic } = require('fcm-v1-token');
|
|
243
|
+
|
|
244
|
+
// Notification with an image and custom data
|
|
245
|
+
await sendToTopic('./service-account.json', 'news', {
|
|
246
|
+
title: 'Breaking',
|
|
247
|
+
body: 'Something happened',
|
|
248
|
+
image: 'https://example.com/photo.png',
|
|
249
|
+
data: { articleId: 42 }, // values are sent as strings
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
// Data-only (silent) message
|
|
253
|
+
await sendToTopic('./service-account.json', 'news', {
|
|
254
|
+
dataOnly: true,
|
|
255
|
+
data: { type: 'sync' },
|
|
256
|
+
});
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
Or build the message yourself and pass it to `sendPush`:
|
|
260
|
+
|
|
261
|
+
```js
|
|
262
|
+
const { buildMessage, sendPush } = require('fcm-v1-token');
|
|
263
|
+
|
|
264
|
+
const message = buildMessage({
|
|
265
|
+
topic: 'news', // or token: '<device-token>', or condition: "'a' in topics"
|
|
266
|
+
title: 'Hello',
|
|
267
|
+
body: 'World',
|
|
268
|
+
channelId: 'promo',
|
|
269
|
+
clickAction: 'FLUTTER_NOTIFICATION_CLICK',
|
|
166
270
|
});
|
|
271
|
+
await sendPush('./service-account.json', message);
|
|
167
272
|
```
|
|
168
273
|
|
|
169
274
|
**Validate only** (do not deliver):
|
|
@@ -202,6 +307,10 @@ No secrets ever leave your machine — the token is created and used locally.
|
|
|
202
307
|
| --- | --- |
|
|
203
308
|
| `getAccessToken(source)` | `{ token, projectId, clientEmail, expiresAt }` |
|
|
204
309
|
| `sendPush(source, message, options?)` | FCM v1 response object |
|
|
310
|
+
| `sendToTopic(source, topic, content, options?)` | FCM v1 response object |
|
|
311
|
+
| `buildMessage(options)` | FCM v1 `message` object for Android, iOS and web |
|
|
312
|
+
| `normalizeTopic(topic)` | bare topic name (strips `/topics/`, validates) |
|
|
313
|
+
| `normalizeData(data)` | FCM `data` map (string values, reserved keys rejected) |
|
|
205
314
|
| `loadServiceAccount(source)` | validated service account object |
|
|
206
315
|
| `saveLastAccount(sa, source)` | persist an account for later runs → config path |
|
|
207
316
|
| `loadLastAccount()` | saved config, or `null` |
|
|
@@ -211,6 +320,7 @@ No secrets ever leave your machine — the token is created and used locally.
|
|
|
211
320
|
|
|
212
321
|
- **`source`** — a file path (string), pasted JSON content (string), or a credentials object.
|
|
213
322
|
- **`options`** — `{ projectId?, dryRun? }`.
|
|
323
|
+
- **`content`** — `{ title?, body?, image?, data?, dataOnly?, sound?, channelId?, clickAction?, priority? }`. `buildMessage` takes the same fields plus one target: `token`, `topic` or `condition`.
|
|
214
324
|
|
|
215
325
|
TypeScript types are bundled (`src/index.d.ts`).
|
|
216
326
|
|
|
@@ -248,6 +358,13 @@ About **1 hour** (3600 seconds). This tool caches it and refreshes it automatica
|
|
|
248
358
|
**How do I send an FCM v1 push notification in Node.js?**
|
|
249
359
|
Use `sendPush(source, message)` — see [Send a push notification](#send-a-push-notification-fcm-v1). It posts to `messages:send` with the right `Authorization: Bearer` header for you.
|
|
250
360
|
|
|
361
|
+
**How do devices subscribe to a topic?**
|
|
362
|
+
In the app, with the Firebase SDK:
|
|
363
|
+
Android `Firebase.messaging.subscribeToTopic("news")` · iOS `Messaging.messaging().subscribe(toTopic: "news")` · Flutter `FirebaseMessaging.instance.subscribeToTopic('news')` · React Native `messaging().subscribeToTopic('news')`. A new subscription can take a little while before topic messages start arriving.
|
|
364
|
+
|
|
365
|
+
**The image shows on Android but not on iOS. Why?**
|
|
366
|
+
iOS needs a Notification Service Extension in the app to download and attach the image. This tool already sends `mutable-content` and `fcm_options.image` for you.
|
|
367
|
+
|
|
251
368
|
**Do I still need the legacy FCM server key?**
|
|
252
369
|
No. The legacy server key is deprecated. The HTTP v1 API uses OAuth 2.0 tokens from a service account, which is exactly what this tool produces.
|
|
253
370
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fcm-v1-token",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Get an FCM v1 OAuth access token from a Firebase service account (cached ~1h, auto-refreshed) and send push notifications. CLI + library for Firebase Cloud Messaging HTTP v1 API.",
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Get an FCM v1 OAuth access token from a Firebase service account (cached ~1h, auto-refreshed) and send push notifications to devices or topics: title, body, image, custom data or data-only. CLI + library for the Firebase Cloud Messaging HTTP v1 API.",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"types": "src/index.d.ts",
|
|
7
7
|
"bin": {
|
|
@@ -12,7 +12,8 @@
|
|
|
12
12
|
"scripts": {
|
|
13
13
|
"start": "node src/cli.js",
|
|
14
14
|
"token": "node src/cli.js token",
|
|
15
|
-
"send": "node src/cli.js send"
|
|
15
|
+
"send": "node src/cli.js send",
|
|
16
|
+
"test": "node --test"
|
|
16
17
|
},
|
|
17
18
|
"keywords": [
|
|
18
19
|
"fcm",
|
|
@@ -22,6 +23,9 @@
|
|
|
22
23
|
"firebase-cloud-messaging",
|
|
23
24
|
"push-notification",
|
|
24
25
|
"push-notifications",
|
|
26
|
+
"data-message",
|
|
27
|
+
"topic-messaging",
|
|
28
|
+
"fcm-topic",
|
|
25
29
|
"oauth",
|
|
26
30
|
"oauth2",
|
|
27
31
|
"access-token",
|
package/src/cli.js
CHANGED
|
@@ -9,6 +9,9 @@ const { version: VERSION } = require('../package.json');
|
|
|
9
9
|
const {
|
|
10
10
|
getAccessToken,
|
|
11
11
|
sendPush,
|
|
12
|
+
buildMessage,
|
|
13
|
+
normalizeTopic,
|
|
14
|
+
normalizeData,
|
|
12
15
|
loadServiceAccount,
|
|
13
16
|
saveLastAccount,
|
|
14
17
|
loadLastAccount,
|
|
@@ -93,11 +96,18 @@ function ask(rl, q, placeholder) {
|
|
|
93
96
|
// Read pasted multi-line JSON. Auto-detects completion once the accumulated
|
|
94
97
|
// text parses as JSON, so the user does not have to type anything after the
|
|
95
98
|
// paste. Typing END on its own line is a manual fallback.
|
|
96
|
-
function readPasted(rl) {
|
|
99
|
+
function readPasted(rl, what = 'the service account JSON') {
|
|
97
100
|
return new Promise((resolve) => {
|
|
98
101
|
const lines = [];
|
|
99
|
-
console.log(
|
|
100
|
-
const cleanup = () =>
|
|
102
|
+
console.log(`\nPaste ${what} now (auto-detected when complete):\n`);
|
|
103
|
+
const cleanup = () => {
|
|
104
|
+
rl.removeListener('line', onLine);
|
|
105
|
+
rl.removeListener('close', onClose);
|
|
106
|
+
};
|
|
107
|
+
const onClose = () => {
|
|
108
|
+
cleanup();
|
|
109
|
+
resolve(lines.join('\n'));
|
|
110
|
+
};
|
|
101
111
|
const onLine = (line) => {
|
|
102
112
|
if (line.trim() === 'END') {
|
|
103
113
|
cleanup();
|
|
@@ -117,6 +127,74 @@ function readPasted(rl) {
|
|
|
117
127
|
}
|
|
118
128
|
};
|
|
119
129
|
rl.on('line', onLine);
|
|
130
|
+
rl.on('close', onClose);
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Read custom data: one key=value per line until an empty line, or a pasted
|
|
135
|
+
// JSON object. Bad lines are rejected on the spot so nothing typed is lost.
|
|
136
|
+
function readData(rl) {
|
|
137
|
+
return new Promise((resolve) => {
|
|
138
|
+
const data = {};
|
|
139
|
+
let jsonLines = null;
|
|
140
|
+
console.log(c.dim(' One key=value per line, empty line to finish — or paste a JSON object.'));
|
|
141
|
+
const prompt = () => {
|
|
142
|
+
rl.setPrompt(c.gray(' › '));
|
|
143
|
+
rl.prompt();
|
|
144
|
+
};
|
|
145
|
+
const finish = (result) => {
|
|
146
|
+
rl.removeListener('line', onLine);
|
|
147
|
+
rl.removeListener('close', onClose);
|
|
148
|
+
resolve(result);
|
|
149
|
+
};
|
|
150
|
+
const onClose = () => finish(data);
|
|
151
|
+
const tryAdd = (obj) => {
|
|
152
|
+
try {
|
|
153
|
+
normalizeData(obj); // reserved keys etc. -> throws
|
|
154
|
+
Object.assign(data, obj);
|
|
155
|
+
return true;
|
|
156
|
+
} catch (err) {
|
|
157
|
+
console.log(c.yellow(` ${err.message}`));
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
const onLine = (line) => {
|
|
162
|
+
const t = line.trim();
|
|
163
|
+
if (jsonLines) {
|
|
164
|
+
jsonLines.push(line);
|
|
165
|
+
try {
|
|
166
|
+
const obj = JSON.parse(jsonLines.join('\n')); // starts with "{" -> an object
|
|
167
|
+
jsonLines = null;
|
|
168
|
+
if (tryAdd(obj)) {
|
|
169
|
+
finish(data);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
prompt();
|
|
173
|
+
} catch (_e) {
|
|
174
|
+
/* JSON not complete yet */
|
|
175
|
+
}
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (t === '') {
|
|
179
|
+
finish(data);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (t.startsWith('{')) {
|
|
183
|
+
jsonLines = [];
|
|
184
|
+
onLine(line);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const eq = t.indexOf('=');
|
|
188
|
+
if (eq <= 0) {
|
|
189
|
+
console.log(c.yellow(' Use key=value (or an empty line to finish).'));
|
|
190
|
+
} else {
|
|
191
|
+
tryAdd({ [t.slice(0, eq).trim()]: t.slice(eq + 1).trim() });
|
|
192
|
+
}
|
|
193
|
+
prompt();
|
|
194
|
+
};
|
|
195
|
+
rl.on('line', onLine);
|
|
196
|
+
rl.on('close', onClose);
|
|
197
|
+
prompt();
|
|
120
198
|
});
|
|
121
199
|
}
|
|
122
200
|
|
|
@@ -271,18 +349,253 @@ async function doToken(source, opts = {}) {
|
|
|
271
349
|
console.log('');
|
|
272
350
|
}
|
|
273
351
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
const body = (await ask(rl, 'Body : ', 'e.g. World')).trim();
|
|
352
|
+
// ---------------------------------------------------------------------------
|
|
353
|
+
// Sending: to a device token or a topic. The message is either composed
|
|
354
|
+
// interactively (with a preview + confirmation) or built straight from flags.
|
|
355
|
+
// ---------------------------------------------------------------------------
|
|
279
356
|
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
357
|
+
const IMAGE_RE = /^https?:\/\/\S+$/i;
|
|
358
|
+
const TARGET_KEYS = ['token', 'topic', 'condition'];
|
|
359
|
+
|
|
360
|
+
function targetFromFlags(flags) {
|
|
361
|
+
if (flags.topic && flags.device) throw new Error('Use either --topic or --device, not both.');
|
|
362
|
+
if (flags.topic) return { topic: normalizeTopic(flags.topic) };
|
|
363
|
+
if (flags.device) return { token: String(flags.device).trim() };
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function hasContentFlags(flags) {
|
|
368
|
+
return flags.title !== undefined || flags.body !== undefined || flags.image !== undefined ||
|
|
369
|
+
flags.data.length > 0 || Boolean(flags.dataOnly);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// --data can be repeated; each value is key=value or a JSON object.
|
|
373
|
+
function parseDataFlags(values) {
|
|
374
|
+
const data = {};
|
|
375
|
+
for (const v of values) {
|
|
376
|
+
const t = String(v).trim();
|
|
377
|
+
if (t.startsWith('{')) {
|
|
378
|
+
let obj;
|
|
379
|
+
try {
|
|
380
|
+
obj = JSON.parse(t);
|
|
381
|
+
} catch (_e) {
|
|
382
|
+
throw new Error(`--data is not valid JSON: ${t}`);
|
|
383
|
+
}
|
|
384
|
+
Object.assign(data, obj);
|
|
385
|
+
} else {
|
|
386
|
+
const eq = t.indexOf('=');
|
|
387
|
+
if (eq <= 0) throw new Error(`--data expects key=value, got: ${t}`);
|
|
388
|
+
data[t.slice(0, eq).trim()] = t.slice(eq + 1);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
return data;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Options that apply to both the flag mode and the interactive composer.
|
|
395
|
+
function extrasFromFlags(flags) {
|
|
396
|
+
const o = {};
|
|
397
|
+
if (flags.sound !== undefined) o.sound = flags.sound;
|
|
398
|
+
if (flags.channel) o.channelId = flags.channel;
|
|
399
|
+
if (flags.clickAction) o.clickAction = flags.clickAction;
|
|
400
|
+
if (flags.priority) o.priority = String(flags.priority).toLowerCase();
|
|
401
|
+
return o;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function contentFromFlags(flags) {
|
|
405
|
+
const o = extrasFromFlags(flags);
|
|
406
|
+
if (flags.title !== undefined) o.title = flags.title;
|
|
407
|
+
if (flags.body !== undefined) o.body = flags.body;
|
|
408
|
+
if (flags.image !== undefined) o.image = flags.image;
|
|
409
|
+
if (flags.data.length) o.data = parseDataFlags(flags.data);
|
|
410
|
+
if (flags.dataOnly) o.dataOnly = true;
|
|
411
|
+
return o;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// --message: JSON content or a path to a .json file.
|
|
415
|
+
function readMessageArg(arg) {
|
|
416
|
+
const t = String(arg).trim();
|
|
417
|
+
if (t.startsWith('{')) return t;
|
|
418
|
+
try {
|
|
419
|
+
return fs.readFileSync(path.resolve(t), 'utf8');
|
|
420
|
+
} catch (_e) {
|
|
421
|
+
throw new Error(`--message is neither JSON nor a readable file: ${t}`);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// A full FCM v1 message pasted/passed by the user. Accepts { message: {...} }
|
|
426
|
+
// too. A given target replaces whatever target the JSON had.
|
|
427
|
+
function customMessage(raw, target) {
|
|
428
|
+
let obj;
|
|
429
|
+
try {
|
|
430
|
+
obj = JSON.parse(String(raw).trim());
|
|
431
|
+
} catch (_e) {
|
|
432
|
+
throw new Error('The custom message is not valid JSON.');
|
|
433
|
+
}
|
|
434
|
+
if (obj && obj.message && typeof obj.message === 'object') obj = obj.message;
|
|
435
|
+
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
|
|
436
|
+
throw new Error('The custom message must be a JSON object.');
|
|
437
|
+
}
|
|
438
|
+
const message = { ...obj };
|
|
439
|
+
if (target) {
|
|
440
|
+
TARGET_KEYS.forEach((k) => delete message[k]);
|
|
441
|
+
Object.assign(message, target);
|
|
442
|
+
}
|
|
443
|
+
if (message.topic) message.topic = normalizeTopic(message.topic);
|
|
444
|
+
if (TARGET_KEYS.filter((k) => message[k]).length > 1) {
|
|
445
|
+
throw new Error('The custom message has more than one target (token/topic/condition).');
|
|
446
|
+
}
|
|
447
|
+
if (message.data !== undefined) message.data = normalizeData(message.data);
|
|
448
|
+
return message;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
async function askTarget(rl, kind) {
|
|
452
|
+
if (kind === 'topic') {
|
|
453
|
+
// eslint-disable-next-line no-constant-condition
|
|
454
|
+
while (true) {
|
|
455
|
+
const t = (await ask(rl, 'Topic : ', 'e.g. news')).trim();
|
|
456
|
+
try {
|
|
457
|
+
return { topic: normalizeTopic(t) };
|
|
458
|
+
} catch (err) {
|
|
459
|
+
console.log(c.yellow(` ${err.message}`));
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
const t = (await ask(rl, 'Device (registration) token: ', 'paste the device token')).trim();
|
|
464
|
+
if (!t) throw new Error('Device token is required.');
|
|
465
|
+
return { token: t };
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
async function askMoreOptions(rl) {
|
|
469
|
+
const o = {};
|
|
470
|
+
const sound = (await ask(rl, 'Sound : ', 'Enter = default, a sound name, or none')).trim();
|
|
471
|
+
if (sound) o.sound = sound;
|
|
472
|
+
const channel = (await ask(rl, 'Android channel : ', 'optional channel id')).trim();
|
|
473
|
+
if (channel) o.channelId = channel;
|
|
474
|
+
const click = (await ask(rl, 'Click action : ', 'optional, e.g. FLUTTER_NOTIFICATION_CLICK')).trim();
|
|
475
|
+
if (click) o.clickAction = click;
|
|
476
|
+
const prio = (await ask(rl, 'Priority : ', 'high (Enter) or normal')).trim().toLowerCase();
|
|
477
|
+
if (prio === 'normal') o.priority = 'normal';
|
|
478
|
+
else if (prio && prio !== 'high') console.log(c.yellow(' Unknown priority — using high.'));
|
|
479
|
+
return o;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// Interactive composer: notification / notification + data / data only / custom JSON.
|
|
483
|
+
async function composeMessage(rl, target, extras = {}) {
|
|
484
|
+
console.log('\n' + c.bold('What do you want to send?') + '\n');
|
|
485
|
+
console.log(` ${c.green('[1]')} Notification ${c.dim('title, body, image — shows in the tray')}`);
|
|
486
|
+
console.log(` ${c.green('[2]')} Notification + data ${c.dim('the same, plus your own key/value data')}`);
|
|
487
|
+
console.log(` ${c.green('[3]')} Data only ${c.dim('silent — your app code handles it')}`);
|
|
488
|
+
console.log(` ${c.green('[4]')} Custom JSON ${c.dim('paste a full FCM v1 message')}\n`);
|
|
489
|
+
const type = (await ask(rl, c.bcyan('Choose: '), 'enter 1-4 (Enter = 1)')).trim() || '1';
|
|
490
|
+
if (!['1', '2', '3', '4'].includes(type)) throw new Error('Invalid choice.');
|
|
491
|
+
|
|
492
|
+
if (type === '4') {
|
|
493
|
+
const raw = await readPasted(rl, 'the FCM message JSON ({"notification": {...}, "data": {...}, ...})');
|
|
494
|
+
return customMessage(raw, target);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
const opts = { ...target, ...extras };
|
|
498
|
+
if (type === '3') {
|
|
499
|
+
opts.dataOnly = true;
|
|
500
|
+
} else {
|
|
501
|
+
while (!opts.title && !opts.body) {
|
|
502
|
+
opts.title = (await ask(rl, 'Title : ', 'e.g. Hello')).trim();
|
|
503
|
+
opts.body = (await ask(rl, 'Body : ', 'e.g. World')).trim();
|
|
504
|
+
if (!opts.title && !opts.body) console.log(c.yellow(' Enter a title or a body.'));
|
|
505
|
+
}
|
|
506
|
+
// eslint-disable-next-line no-constant-condition
|
|
507
|
+
while (true) {
|
|
508
|
+
const img = (await ask(rl, 'Image : ', 'optional https:// URL — Enter to skip')).trim();
|
|
509
|
+
if (!img || IMAGE_RE.test(img)) {
|
|
510
|
+
if (img) opts.image = img;
|
|
511
|
+
break;
|
|
512
|
+
}
|
|
513
|
+
console.log(c.yellow(' The image must be an http(s) URL.'));
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
if (type === '2' || type === '3') {
|
|
518
|
+
console.log('\n' + c.bold('Data') + (type === '2' ? c.dim(' (optional)') : ''));
|
|
519
|
+
// eslint-disable-next-line no-constant-condition
|
|
520
|
+
while (true) {
|
|
521
|
+
opts.data = await readData(rl);
|
|
522
|
+
if (type === '2' || Object.keys(opts.data).length) break;
|
|
523
|
+
console.log(c.yellow(' A data-only message needs at least one key=value.'));
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
if (type !== '3' && Object.keys(extras).length === 0) {
|
|
528
|
+
const more = (await ask(rl, 'More options (sound, channel, click action, priority)? ', 'y/N')).trim().toLowerCase();
|
|
529
|
+
if (more === 'y' || more === 'yes') Object.assign(opts, await askMoreOptions(rl));
|
|
530
|
+
}
|
|
531
|
+
return buildMessage(opts);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function describeTarget(message) {
|
|
535
|
+
if (message.topic) return `topic "${message.topic}"`;
|
|
536
|
+
if (message.condition) return `condition ${message.condition}`;
|
|
537
|
+
return 'the device';
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function printSendResult(message, res, dryRun, json) {
|
|
541
|
+
if (json) {
|
|
542
|
+
console.log(JSON.stringify(res, null, 2));
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
const where = describeTarget(message);
|
|
546
|
+
if (dryRun) {
|
|
547
|
+
console.log(c.bgreen('\n✓ Valid.') + ` FCM accepted the message for ${where} ` +
|
|
548
|
+
c.dim('(dry run — nothing was delivered).'));
|
|
549
|
+
} else {
|
|
550
|
+
console.log(c.bgreen(`\n✓ Sent to ${where}.`));
|
|
551
|
+
}
|
|
552
|
+
if (res && res.name) console.log(` ${c.dim('Message ID')} : ${c.cyan(res.name)}`);
|
|
553
|
+
if (message.topic && !dryRun) {
|
|
554
|
+
console.log(c.dim(' Every device subscribed to this topic receives it. FCM does not report how many that is.'));
|
|
555
|
+
}
|
|
556
|
+
console.log('');
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
async function doSend(rl, source, kind, flags) {
|
|
560
|
+
const target = targetFromFlags(flags);
|
|
561
|
+
const fromFlags = Boolean(flags.message) || hasContentFlags(flags);
|
|
562
|
+
let message;
|
|
563
|
+
|
|
564
|
+
if (flags.message) {
|
|
565
|
+
message = customMessage(readMessageArg(flags.message), target);
|
|
566
|
+
if (!TARGET_KEYS.some((k) => message[k])) Object.assign(message, await askTarget(rl, kind));
|
|
567
|
+
} else {
|
|
568
|
+
const to = target || (await askTarget(rl, kind));
|
|
569
|
+
message = fromFlags
|
|
570
|
+
? buildMessage({ ...to, ...contentFromFlags(flags) })
|
|
571
|
+
: await composeMessage(rl, to, extrasFromFlags(flags));
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
let dryRun = Boolean(flags.dryRun);
|
|
575
|
+
|
|
576
|
+
// Interactive: always show what will be sent and ask before sending.
|
|
577
|
+
if (!fromFlags && !flags.yes) {
|
|
578
|
+
console.log('\n' + c.bold('Message preview') + c.dim(' (FCM v1 JSON)'));
|
|
579
|
+
console.log(JSON.stringify(message, null, 2).split('\n').map((l) => ' ' + c.cyan(l)).join('\n'));
|
|
580
|
+
if (message.topic && !dryRun) {
|
|
581
|
+
console.log(c.yellow(`\n ⚠ This goes to EVERY device subscribed to topic "${message.topic}".`));
|
|
582
|
+
}
|
|
583
|
+
const answer = (await ask(
|
|
584
|
+
rl,
|
|
585
|
+
c.bcyan(dryRun ? '\nValidate it now (dry run)? ' : '\nSend now? '),
|
|
586
|
+
dryRun ? 'Y/n' : 'Y = send · d = dry run (validate only) · n = cancel'
|
|
587
|
+
)).trim().toLowerCase();
|
|
588
|
+
if (answer === 'd' || answer === 'dry') {
|
|
589
|
+
dryRun = true;
|
|
590
|
+
} else if (!['', 'y', 'yes'].includes(answer)) {
|
|
591
|
+
console.log(c.dim('\nCancelled — nothing was sent.\n'));
|
|
592
|
+
return null;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
const res = await sendPush(source, message, { dryRun });
|
|
597
|
+
printSendResult(message, res, dryRun, flags.json);
|
|
598
|
+
return res;
|
|
286
599
|
}
|
|
287
600
|
|
|
288
601
|
function showSaved() {
|
|
@@ -327,25 +640,28 @@ async function interactive() {
|
|
|
327
640
|
console.log(line);
|
|
328
641
|
console.log(c.bold('What do you want to do?') + '\n');
|
|
329
642
|
console.log(` ${c.green('[1]')} Get access token`);
|
|
330
|
-
console.log(` ${c.green('[2]')} Send a test push`);
|
|
331
|
-
console.log(` ${c.green('[3]')}
|
|
332
|
-
console.log(` ${c.green('[4]')}
|
|
333
|
-
console.log(` ${c.green('[5]')}
|
|
643
|
+
console.log(` ${c.green('[2]')} Send a test push to a device`);
|
|
644
|
+
console.log(` ${c.green('[3]')} Send a real notification to a topic`);
|
|
645
|
+
console.log(` ${c.green('[4]')} Change service account`);
|
|
646
|
+
console.log(` ${c.green('[5]')} Forget saved service account`);
|
|
647
|
+
console.log(` ${c.green('[6]')} Exit\n`);
|
|
334
648
|
|
|
335
|
-
const choice = (await ask(rl, c.bcyan('Choose: '), 'enter 1-
|
|
649
|
+
const choice = (await ask(rl, c.bcyan('Choose: '), 'enter 1-6 and press Enter')).trim();
|
|
336
650
|
|
|
337
651
|
try {
|
|
338
652
|
if (choice === '1') {
|
|
339
653
|
await doToken(savedSource(saved));
|
|
340
654
|
} else if (choice === '2') {
|
|
341
|
-
await doSend(rl, savedSource(saved));
|
|
655
|
+
await doSend(rl, savedSource(saved), 'device', EMPTY_FLAGS);
|
|
342
656
|
} else if (choice === '3') {
|
|
343
|
-
await
|
|
657
|
+
await doSend(rl, savedSource(saved), 'topic', EMPTY_FLAGS);
|
|
344
658
|
} else if (choice === '4') {
|
|
659
|
+
await setupServiceAccount(rl);
|
|
660
|
+
} else if (choice === '5') {
|
|
345
661
|
forgetLastAccount();
|
|
346
662
|
console.log(c.yellow('\nForgotten. Setting up a new one.'));
|
|
347
663
|
await setupServiceAccount(rl);
|
|
348
|
-
} else if (choice === '
|
|
664
|
+
} else if (choice === '6' || choice.toLowerCase() === 'exit' || choice === '') {
|
|
349
665
|
console.log(c.dim('\nBye.\n'));
|
|
350
666
|
return;
|
|
351
667
|
} else {
|
|
@@ -373,7 +689,7 @@ function printBanner() {
|
|
|
373
689
|
console.log(' ' + rule);
|
|
374
690
|
console.log(' ' + c.dim('Turns a service account key into a 1-hour access token'));
|
|
375
691
|
console.log(' ' + c.dim('for the FCM v1 API — cached & auto-refreshed — and can'));
|
|
376
|
-
console.log(' ' + c.dim('send push
|
|
692
|
+
console.log(' ' + c.dim('send push to a device or a topic. Remembers your account.'));
|
|
377
693
|
console.log('');
|
|
378
694
|
}
|
|
379
695
|
|
|
@@ -387,7 +703,8 @@ Run with no arguments for an interactive menu. Your service account
|
|
|
387
703
|
Usage:
|
|
388
704
|
fcm-token Interactive menu (remembers last account)
|
|
389
705
|
fcm-token token [source] Print an access token
|
|
390
|
-
fcm-token send [source] Send a
|
|
706
|
+
fcm-token send [source] Send a push to a device (interactive prompts)
|
|
707
|
+
fcm-token topic [source] Send a notification to a topic (interactive)
|
|
391
708
|
fcm-token use <source> Set / replace the saved service account
|
|
392
709
|
fcm-token whoami Show the saved service account
|
|
393
710
|
fcm-token forget Remove the saved service account
|
|
@@ -402,40 +719,134 @@ Options (for "token"):
|
|
|
402
719
|
--raw Print only the token (for scripting)
|
|
403
720
|
--no-copy Do not copy the token to the clipboard
|
|
404
721
|
|
|
722
|
+
Options (for "send" / "topic") — with any content option it sends right away,
|
|
723
|
+
without prompts; without them you get the interactive composer:
|
|
724
|
+
--topic <name> Send to every device subscribed to this topic
|
|
725
|
+
--device <token> Send to one device registration token
|
|
726
|
+
--title <text> Notification title
|
|
727
|
+
--body <text> Notification body
|
|
728
|
+
--image <url> Image URL (Android, iOS and web)
|
|
729
|
+
--data <key=value> Custom data; repeat it, or pass a JSON object
|
|
730
|
+
--data-only Silent data message (no title/body/image)
|
|
731
|
+
--message <json|file> A full custom FCM v1 message (JSON or .json file)
|
|
732
|
+
--sound <name|none> Notification sound (default: "default")
|
|
733
|
+
--channel <id> Android notification channel id
|
|
734
|
+
--click-action <name> Android click_action / iOS category
|
|
735
|
+
--priority <high|normal> Delivery priority (default: high)
|
|
736
|
+
--dry-run Validate with FCM only — nothing is delivered
|
|
737
|
+
--yes, -y Interactive mode: send without the confirm step
|
|
738
|
+
--json Print the raw FCM response as JSON
|
|
739
|
+
|
|
405
740
|
Examples:
|
|
406
741
|
npx fcm-v1-token # menu, remembers your file
|
|
407
742
|
fcm-token use ./service-account.json # remember this file
|
|
408
743
|
fcm-token token --raw # print token using saved account
|
|
409
744
|
TOKEN=$(fcm-token token --raw)
|
|
410
|
-
fcm-token send # push using saved account
|
|
745
|
+
fcm-token send # push to a device, using saved account
|
|
746
|
+
fcm-token topic # notification to a topic (interactive)
|
|
747
|
+
fcm-token send --topic news --title "Hi" --body "Hello" \\
|
|
748
|
+
--image https://example.com/a.png --data screen=home --data id=42
|
|
749
|
+
fcm-token send --topic news --data-only --data '{"type":"sync"}'
|
|
750
|
+
fcm-token send --topic news --title "Test" --dry-run
|
|
411
751
|
`);
|
|
412
752
|
}
|
|
413
753
|
|
|
754
|
+
// Flags that take a value, and boolean switches. Names map to keys in `flags`.
|
|
755
|
+
const VALUE_FLAGS = {
|
|
756
|
+
topic: 'topic',
|
|
757
|
+
device: 'device',
|
|
758
|
+
title: 'title',
|
|
759
|
+
body: 'body',
|
|
760
|
+
image: 'image',
|
|
761
|
+
data: 'data',
|
|
762
|
+
message: 'message',
|
|
763
|
+
sound: 'sound',
|
|
764
|
+
channel: 'channel',
|
|
765
|
+
'click-action': 'clickAction',
|
|
766
|
+
priority: 'priority',
|
|
767
|
+
};
|
|
768
|
+
const BOOL_FLAGS = {
|
|
769
|
+
help: 'help',
|
|
770
|
+
json: 'json',
|
|
771
|
+
raw: 'raw',
|
|
772
|
+
'no-copy': 'noCopy',
|
|
773
|
+
'data-only': 'dataOnly',
|
|
774
|
+
'dry-run': 'dryRun',
|
|
775
|
+
yes: 'yes',
|
|
776
|
+
};
|
|
777
|
+
const SHORT_FLAGS = { h: 'help', y: 'yes' };
|
|
778
|
+
const EMPTY_FLAGS = Object.freeze({ data: [] });
|
|
779
|
+
|
|
780
|
+
// Supports "--flag value", "--flag=value", repeated --data and "--" to end flags.
|
|
781
|
+
function parseArgs(argv) {
|
|
782
|
+
const flags = { data: [] };
|
|
783
|
+
const positional = [];
|
|
784
|
+
for (let i = 0; i < argv.length; i++) {
|
|
785
|
+
const a = argv[i];
|
|
786
|
+
if (a === '--') {
|
|
787
|
+
positional.push(...argv.slice(i + 1));
|
|
788
|
+
break;
|
|
789
|
+
}
|
|
790
|
+
if (/^-[a-zA-Z]$/.test(a)) {
|
|
791
|
+
const key = SHORT_FLAGS[a[1]];
|
|
792
|
+
if (!key) throw new Error(`Unknown option ${a}. Run with --help.`);
|
|
793
|
+
flags[key] = true;
|
|
794
|
+
continue;
|
|
795
|
+
}
|
|
796
|
+
if (!a.startsWith('--')) {
|
|
797
|
+
positional.push(a);
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
let name = a.slice(2);
|
|
801
|
+
let value;
|
|
802
|
+
const eq = name.indexOf('=');
|
|
803
|
+
if (eq !== -1) {
|
|
804
|
+
value = name.slice(eq + 1);
|
|
805
|
+
name = name.slice(0, eq);
|
|
806
|
+
}
|
|
807
|
+
if (BOOL_FLAGS[name]) {
|
|
808
|
+
flags[BOOL_FLAGS[name]] = true;
|
|
809
|
+
continue;
|
|
810
|
+
}
|
|
811
|
+
const key = VALUE_FLAGS[name];
|
|
812
|
+
if (!key) throw new Error(`Unknown option --${name}. Run with --help.`);
|
|
813
|
+
if (value === undefined) {
|
|
814
|
+
if (i + 1 >= argv.length) throw new Error(`--${name} needs a value.`);
|
|
815
|
+
value = argv[++i];
|
|
816
|
+
}
|
|
817
|
+
if (key === 'data') flags.data.push(value);
|
|
818
|
+
else flags[key] = value;
|
|
819
|
+
}
|
|
820
|
+
return { flags, positional };
|
|
821
|
+
}
|
|
822
|
+
|
|
414
823
|
async function main() {
|
|
415
|
-
const
|
|
824
|
+
const { flags, positional } = parseArgs(process.argv.slice(2));
|
|
416
825
|
|
|
417
|
-
if (
|
|
826
|
+
if (flags.help) {
|
|
418
827
|
printHelp();
|
|
419
828
|
return;
|
|
420
829
|
}
|
|
421
830
|
|
|
422
831
|
const opts = {
|
|
423
|
-
json:
|
|
424
|
-
raw:
|
|
425
|
-
copy: !
|
|
832
|
+
json: Boolean(flags.json),
|
|
833
|
+
raw: Boolean(flags.raw),
|
|
834
|
+
copy: !flags.noCopy,
|
|
426
835
|
};
|
|
427
|
-
const
|
|
836
|
+
const wantsSend = Boolean(flags.topic || flags.device || flags.message) || hasContentFlags(flags);
|
|
428
837
|
|
|
429
|
-
const COMMANDS = new Set(['token', 'send', 'use', 'whoami', 'forget']);
|
|
838
|
+
const COMMANDS = new Set(['token', 'send', 'topic', 'use', 'whoami', 'forget']);
|
|
430
839
|
let command;
|
|
431
840
|
let sourceArg;
|
|
432
841
|
if (positional.length && COMMANDS.has(positional[0])) {
|
|
433
842
|
command = positional[0];
|
|
434
843
|
sourceArg = positional[1];
|
|
435
844
|
} else if (positional.length) {
|
|
436
|
-
// First positional is a source -> default to token.
|
|
437
|
-
command = 'token';
|
|
845
|
+
// First positional is a source -> default to token (or send, if send flags were given).
|
|
846
|
+
command = wantsSend ? 'send' : 'token';
|
|
438
847
|
sourceArg = positional[0];
|
|
848
|
+
} else if (wantsSend) {
|
|
849
|
+
command = 'send';
|
|
439
850
|
}
|
|
440
851
|
|
|
441
852
|
// No command at all -> interactive menu.
|
|
@@ -473,10 +884,10 @@ async function main() {
|
|
|
473
884
|
return;
|
|
474
885
|
}
|
|
475
886
|
|
|
476
|
-
if (command === 'send') {
|
|
887
|
+
if (command === 'send' || command === 'topic') {
|
|
477
888
|
await withRL(async (rl) => {
|
|
478
889
|
const source = await resolveSource(rl, sourceArg);
|
|
479
|
-
await doSend(rl, source);
|
|
890
|
+
await doSend(rl, source, command === 'topic' ? 'topic' : 'device', flags);
|
|
480
891
|
});
|
|
481
892
|
return;
|
|
482
893
|
}
|
package/src/index.d.ts
CHANGED
|
@@ -51,6 +51,60 @@ export function sendPush(
|
|
|
51
51
|
options?: SendOptions
|
|
52
52
|
): Promise<Record<string, unknown>>;
|
|
53
53
|
|
|
54
|
+
/** What to show/deliver — everything except the target. */
|
|
55
|
+
export interface MessageContent {
|
|
56
|
+
/** Notification title (a notification needs a title or a body). */
|
|
57
|
+
title?: string;
|
|
58
|
+
/** Notification body. */
|
|
59
|
+
body?: string;
|
|
60
|
+
/** http(s) image URL — set for Android, iOS (needs a service extension) and web. */
|
|
61
|
+
image?: string;
|
|
62
|
+
/** Custom key/value data. Non-string values are JSON-encoded. */
|
|
63
|
+
data?: Record<string, unknown>;
|
|
64
|
+
/** true => silent data message (no title/body/image); needs `data`. */
|
|
65
|
+
dataOnly?: boolean;
|
|
66
|
+
/** Notification sound; default "default". Use "none" (or false) for no sound field. */
|
|
67
|
+
sound?: string | false;
|
|
68
|
+
/** Android notification channel id. */
|
|
69
|
+
channelId?: string;
|
|
70
|
+
/** Android click_action / iOS category. */
|
|
71
|
+
clickAction?: string;
|
|
72
|
+
/** Delivery priority; default "high". */
|
|
73
|
+
priority?: 'high' | 'normal';
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** buildMessage() options: content plus exactly one target. */
|
|
77
|
+
export interface BuildMessageOptions extends MessageContent {
|
|
78
|
+
/** Device registration token. */
|
|
79
|
+
token?: string;
|
|
80
|
+
/** Topic name, e.g. "news" (a "/topics/" prefix is accepted). */
|
|
81
|
+
topic?: string;
|
|
82
|
+
/** Topic condition, e.g. "'news' in topics && 'sports' in topics". */
|
|
83
|
+
condition?: string;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Build a cross-platform FCM v1 message (Android, iOS, web) from simple options. */
|
|
87
|
+
export function buildMessage(options: BuildMessageOptions): Record<string, unknown>;
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Send a notification or data-only message to every device subscribed to a topic.
|
|
91
|
+
* Resolves to the FCM response, e.g. { name: 'projects/x/messages/123' }.
|
|
92
|
+
*/
|
|
93
|
+
export function sendToTopic(
|
|
94
|
+
source: Source,
|
|
95
|
+
topic: string,
|
|
96
|
+
content: MessageContent,
|
|
97
|
+
options?: SendOptions
|
|
98
|
+
): Promise<Record<string, unknown>>;
|
|
99
|
+
|
|
100
|
+
/** Validate a topic name and strip an optional "/topics/" prefix. */
|
|
101
|
+
export function normalizeTopic(topic: string): string;
|
|
102
|
+
|
|
103
|
+
/** Turn data into FCM's string-to-string map; throws on reserved keys. */
|
|
104
|
+
export function normalizeData(
|
|
105
|
+
data: Record<string, unknown> | null | undefined
|
|
106
|
+
): Record<string, string> | undefined;
|
|
107
|
+
|
|
54
108
|
/** Remember a service account for later runs. */
|
|
55
109
|
export function saveLastAccount(
|
|
56
110
|
sa: ServiceAccount,
|
package/src/index.js
CHANGED
|
@@ -157,6 +157,152 @@ async function sendPush(source, message, options = {}) {
|
|
|
157
157
|
return data;
|
|
158
158
|
}
|
|
159
159
|
|
|
160
|
+
// ---------------------------------------------------------------------------
|
|
161
|
+
// Message builder: simple options -> a cross-platform FCM v1 "message" object.
|
|
162
|
+
// ---------------------------------------------------------------------------
|
|
163
|
+
|
|
164
|
+
// FCM topic names: letters, numbers and - _ . ~ % (the "/topics/" prefix is optional).
|
|
165
|
+
const TOPIC_RE = /^[a-zA-Z0-9\-_.~%]{1,900}$/;
|
|
166
|
+
// Keys FCM rejects inside "data".
|
|
167
|
+
const RESERVED_DATA_KEYS = new Set(['from', 'notification', 'message_type']);
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Validate a topic name and strip an optional "/topics/" prefix.
|
|
171
|
+
* @param {string} topic
|
|
172
|
+
* @returns {string} bare topic name, e.g. "news"
|
|
173
|
+
*/
|
|
174
|
+
function normalizeTopic(topic) {
|
|
175
|
+
let t = String(topic == null ? '' : topic).trim();
|
|
176
|
+
if (t.startsWith('/topics/')) t = t.slice('/topics/'.length);
|
|
177
|
+
if (!t) throw new Error('Topic name is required.');
|
|
178
|
+
if (!TOPIC_RE.test(t)) {
|
|
179
|
+
throw new Error(`Invalid topic name "${t}". Use only letters, numbers and - _ . ~ %`);
|
|
180
|
+
}
|
|
181
|
+
return t;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* FCM "data" must be a flat map of string -> string. Non-string values are
|
|
186
|
+
* JSON-encoded; reserved keys throw.
|
|
187
|
+
* @param {object} data
|
|
188
|
+
* @returns {Record<string,string>|undefined} undefined when empty
|
|
189
|
+
*/
|
|
190
|
+
function normalizeData(data) {
|
|
191
|
+
if (data == null) return undefined;
|
|
192
|
+
if (typeof data !== 'object' || Array.isArray(data)) {
|
|
193
|
+
throw new Error('data must be an object of key/value pairs.');
|
|
194
|
+
}
|
|
195
|
+
const out = {};
|
|
196
|
+
for (const [rawKey, value] of Object.entries(data)) {
|
|
197
|
+
const key = String(rawKey).trim();
|
|
198
|
+
if (!key) throw new Error('Data keys cannot be empty.');
|
|
199
|
+
if (RESERVED_DATA_KEYS.has(key) || key.startsWith('google.') || key.startsWith('gcm.')) {
|
|
200
|
+
throw new Error(`"${key}" is a reserved FCM data key — use another name.`);
|
|
201
|
+
}
|
|
202
|
+
out[key] = value == null ? '' : typeof value === 'string' ? value : JSON.stringify(value);
|
|
203
|
+
}
|
|
204
|
+
return Object.keys(out).length ? out : undefined;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Build an FCM v1 message that works on Android, iOS and web from simple options.
|
|
209
|
+
*
|
|
210
|
+
* - Notification: title/body (+ optional image) shown in the system tray.
|
|
211
|
+
* Images are set for Android/web (notification.image) and iOS
|
|
212
|
+
* (apns.fcm_options.image + mutable-content).
|
|
213
|
+
* - Data only (`dataOnly: true`): no visible notification; delivered to your
|
|
214
|
+
* app's code. Sent high priority on Android and as a background push on iOS.
|
|
215
|
+
*
|
|
216
|
+
* @param {object} opts
|
|
217
|
+
* @returns {object} FCM v1 "message" object, ready for sendPush()
|
|
218
|
+
*/
|
|
219
|
+
function buildMessage(opts = {}) {
|
|
220
|
+
const {
|
|
221
|
+
token, topic, condition,
|
|
222
|
+
title, body, image, data, dataOnly,
|
|
223
|
+
sound = 'default', channelId, clickAction, priority = 'high',
|
|
224
|
+
} = opts;
|
|
225
|
+
|
|
226
|
+
const targets = [token, topic, condition].filter((v) => v != null && String(v).trim() !== '');
|
|
227
|
+
if (targets.length !== 1) {
|
|
228
|
+
throw new Error('Set exactly one target: token, topic or condition.');
|
|
229
|
+
}
|
|
230
|
+
if (priority !== 'high' && priority !== 'normal') {
|
|
231
|
+
throw new Error('priority must be "high" or "normal".');
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const message = {};
|
|
235
|
+
if (token) message.token = String(token).trim();
|
|
236
|
+
if (topic) message.topic = normalizeTopic(topic);
|
|
237
|
+
if (condition) message.condition = String(condition).trim();
|
|
238
|
+
|
|
239
|
+
const payload = normalizeData(data);
|
|
240
|
+
if (payload) message.data = payload;
|
|
241
|
+
|
|
242
|
+
if (dataOnly) {
|
|
243
|
+
if (!payload) throw new Error('A data-only message needs at least one data key/value.');
|
|
244
|
+
if (title || body || image) {
|
|
245
|
+
throw new Error('A data-only message cannot have a title, body or image.');
|
|
246
|
+
}
|
|
247
|
+
message.android = { priority };
|
|
248
|
+
message.apns = {
|
|
249
|
+
headers: { 'apns-push-type': 'background', 'apns-priority': '5' },
|
|
250
|
+
payload: { aps: { 'content-available': 1 } },
|
|
251
|
+
};
|
|
252
|
+
return message;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (!title && !body) {
|
|
256
|
+
throw new Error('A notification needs a title or a body (or set dataOnly with data).');
|
|
257
|
+
}
|
|
258
|
+
if (image && !/^https?:\/\/\S+$/i.test(String(image))) {
|
|
259
|
+
throw new Error('image must be an http(s) URL.');
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
message.notification = {};
|
|
263
|
+
if (title) message.notification.title = String(title);
|
|
264
|
+
if (body) message.notification.body = String(body);
|
|
265
|
+
if (image) message.notification.image = String(image);
|
|
266
|
+
|
|
267
|
+
const playSound = sound && sound !== 'none';
|
|
268
|
+
|
|
269
|
+
const androidNote = {};
|
|
270
|
+
if (playSound) androidNote.sound = sound;
|
|
271
|
+
if (channelId) androidNote.channel_id = String(channelId);
|
|
272
|
+
if (clickAction) androidNote.click_action = String(clickAction);
|
|
273
|
+
const android = {};
|
|
274
|
+
if (priority === 'normal') android.priority = 'normal'; // notifications default to high
|
|
275
|
+
if (Object.keys(androidNote).length) android.notification = androidNote;
|
|
276
|
+
if (Object.keys(android).length) message.android = android;
|
|
277
|
+
|
|
278
|
+
const aps = {};
|
|
279
|
+
if (playSound) aps.sound = sound;
|
|
280
|
+
if (image) aps['mutable-content'] = 1; // lets the iOS service extension attach the image
|
|
281
|
+
if (clickAction) aps.category = String(clickAction);
|
|
282
|
+
const apns = {};
|
|
283
|
+
if (priority === 'normal') apns.headers = { 'apns-priority': '5' };
|
|
284
|
+
if (Object.keys(aps).length) apns.payload = { aps };
|
|
285
|
+
if (image) apns.fcm_options = { image: String(image) };
|
|
286
|
+
if (Object.keys(apns).length) message.apns = apns;
|
|
287
|
+
|
|
288
|
+
return message;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Send a notification (or data-only message) to every device subscribed to a topic.
|
|
293
|
+
*
|
|
294
|
+
* @param {string|object} source - service account file path, JSON content, or object
|
|
295
|
+
* @param {string} topic - topic name, e.g. "news" (or "/topics/news")
|
|
296
|
+
* @param {object} content - buildMessage() options without a target:
|
|
297
|
+
* { title, body, image, data, dataOnly, sound, channelId, clickAction, priority }
|
|
298
|
+
* @param {object} [options] - { projectId?, dryRun? }
|
|
299
|
+
* @returns {Promise<object>} FCM response, e.g. { name: 'projects/x/messages/123' }
|
|
300
|
+
*/
|
|
301
|
+
async function sendToTopic(source, topic, content = {}, options = {}) {
|
|
302
|
+
const { token: _t, condition: _c, ...rest } = content || {};
|
|
303
|
+
return sendPush(source, buildMessage({ ...rest, topic }), options);
|
|
304
|
+
}
|
|
305
|
+
|
|
160
306
|
/** Clear the in-memory token client cache (testing / key rotation). */
|
|
161
307
|
function clearCache() {
|
|
162
308
|
clientCache.clear();
|
|
@@ -247,6 +393,10 @@ function forgetLastAccount() {
|
|
|
247
393
|
module.exports = {
|
|
248
394
|
getAccessToken,
|
|
249
395
|
sendPush,
|
|
396
|
+
sendToTopic,
|
|
397
|
+
buildMessage,
|
|
398
|
+
normalizeTopic,
|
|
399
|
+
normalizeData,
|
|
250
400
|
loadServiceAccount,
|
|
251
401
|
clearCache,
|
|
252
402
|
// persistence
|