@miguelmorales13/nestkit 0.22.0 → 0.25.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.
@@ -0,0 +1,73 @@
1
+ import type { FcmOptions, FirebaseServiceAccount } from '../push.options.js';
2
+ import type { PushChannelPort, PushDevice, PushFailure, ResolvedPushMessage } from '../push.port.js';
3
+ /**
4
+ * Firebase Cloud Messaging over its HTTP v1 API, with `fetch`.
5
+ *
6
+ * Not `firebase-admin`: it pulls half of Google Cloud into the bundle for
7
+ * what is one POST with a bearer token. The token is an OAuth2 access token
8
+ * obtained by signing a JWT with the service account's private key — the
9
+ * same thing the SDK does, in thirty visible lines — and cached until it is
10
+ * about to expire.
11
+ *
12
+ * The message shape is FCM's, one block per platform, because that is where
13
+ * the platforms disagree: what is a native button on the web is a
14
+ * registered category on iOS and does not exist on Android unless the app
15
+ * draws the notification itself. Everything the app might need to do that
16
+ * travels in `data`, as strings, since FCM carries nothing else there.
17
+ */
18
+ export declare class FcmChannel implements PushChannelPort {
19
+ readonly kind: "fcm";
20
+ private readonly account;
21
+ private readonly fetchImpl;
22
+ private token?;
23
+ private tokenInFlight?;
24
+ constructor(options: FcmOptions);
25
+ get projectId(): string;
26
+ send(device: PushDevice, message: ResolvedPushMessage): Promise<{
27
+ id: string | null;
28
+ } | Omit<PushFailure, 'device'>>;
29
+ sendToTopic(topic: string, message: ResolvedPushMessage): Promise<{
30
+ id: string | null;
31
+ }>;
32
+ subscribeToTopic(tokens: string[], topic: string): Promise<void>;
33
+ unsubscribeFromTopic(tokens: string[], topic: string): Promise<void>;
34
+ /** The FCM v1 message for a target. Exported through the instance so a test can pin the exact bytes. */
35
+ buildMessage(target: {
36
+ token: string;
37
+ } | {
38
+ topic: string;
39
+ }, message: ResolvedPushMessage): Record<string, unknown>;
40
+ private post;
41
+ private topicBatch;
42
+ /**
43
+ * The OAuth2 access token, minted from a self-signed JWT and kept until
44
+ * a minute before it expires. Concurrent sends share one in-flight
45
+ * request rather than each minting their own.
46
+ */
47
+ private accessToken;
48
+ private mintAccessToken;
49
+ }
50
+ /** Parsed JSON, the JSON in a string, or a path to it — every way the credential shows up. */
51
+ export declare function parseServiceAccount(input: FirebaseServiceAccount | string): FirebaseServiceAccount;
52
+ /**
53
+ * One message, four dialects.
54
+ *
55
+ * - `data` carries `link`, `actions` and `category` on every platform, so
56
+ * an app that renders its own notification has the whole picture.
57
+ * - Android's system notification has no buttons; only `channel_id`, sound
58
+ * and the picture map onto it. Buttons there mean `dataOnly` and the app
59
+ * drawing the notification.
60
+ * - iOS gets `category` (the buttons the app registered under that name),
61
+ * `badge`, `sound`, and `mutable-content` when there is a picture, which
62
+ * is what lets a Notification Service Extension download it. A
63
+ * `dataOnly` message is a background push: `content-available`, priority
64
+ * 5 and push-type `background`, or APNs drops it.
65
+ * - Web gets native `actions`, plus `fcm_options.link` when the link is
66
+ * `https` — FCM refuses anything else there — and the same link in
67
+ * `data` for the service worker's `notificationclick`.
68
+ */
69
+ export declare function toFcmMessage(target: {
70
+ token: string;
71
+ } | {
72
+ topic: string;
73
+ }, m: ResolvedPushMessage): Record<string, unknown>;
@@ -0,0 +1,62 @@
1
+ import type { WebPushOptions } from '../push.options.js';
2
+ import type { PushChannelPort, PushDevice, PushFailure, ResolvedPushMessage } from '../push.port.js';
3
+ /** The two calls this adapter makes; what a test hands in instead of the library. */
4
+ export interface WebPushLike {
5
+ setVapidDetails(subject: string, publicKey: string, privateKey: string): void;
6
+ sendNotification(subscription: {
7
+ endpoint: string;
8
+ keys: {
9
+ p256dh: string;
10
+ auth: string;
11
+ };
12
+ }, payload: string, options?: {
13
+ TTL?: number;
14
+ urgency?: string;
15
+ topic?: string;
16
+ }): Promise<{
17
+ statusCode: number;
18
+ }>;
19
+ }
20
+ /**
21
+ * The payload a Web Push subscription receives, as JSON. The service
22
+ * worker renders it — `showNotification(title, { body, icon, image, badge,
23
+ * actions, data, tag })` maps one to one — and handles `notificationclick`
24
+ * with `data.link` and `data.actions`. See the README for the worker.
25
+ */
26
+ export interface WebPushPayload {
27
+ title: string;
28
+ body: string;
29
+ icon?: string;
30
+ image?: string;
31
+ badge?: number;
32
+ tag?: string;
33
+ link?: string;
34
+ actions?: {
35
+ action: string;
36
+ title: string;
37
+ icon?: string;
38
+ link?: string;
39
+ }[];
40
+ data?: Record<string, unknown>;
41
+ }
42
+ /**
43
+ * Browsers, through the Web Push protocol with VAPID keys — the `web-push`
44
+ * package, loaded lazily so an app with only native devices never does.
45
+ *
46
+ * `404`/`410` are the push service saying the subscription is gone (the
47
+ * person revoked it, or the browser rotated it): `stale`. Everything else
48
+ * is a failure to report, not a reason to delete.
49
+ */
50
+ export declare class WebPushChannel implements PushChannelPort {
51
+ private readonly options;
52
+ readonly kind: "webpush";
53
+ private libPromise?;
54
+ constructor(options: WebPushOptions, lib?: WebPushLike);
55
+ private lib;
56
+ private configure;
57
+ /** The JSON the worker gets. On the instance so a test can pin it. */
58
+ buildPayload(message: ResolvedPushMessage): WebPushPayload;
59
+ send(device: PushDevice, message: ResolvedPushMessage): Promise<{
60
+ id: string | null;
61
+ } | Omit<PushFailure, 'device'>>;
62
+ }
@@ -0,0 +1,449 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+ var _chunkAXMW5JF7cjs = require('../chunk-AXMW5JF7.cjs');
4
+ require('../chunk-Y72D5L6I.cjs');
5
+ require('../chunk-SDWHKPXI.cjs');
6
+
7
+
8
+ var _chunkPNK5WMPPcjs = require('../chunk-PNK5WMPP.cjs');
9
+
10
+
11
+ var _chunk2REOCMUDcjs = require('../chunk-2REOCMUD.cjs');
12
+
13
+ // src/push/push.port.ts
14
+ var PUSH = /* @__PURE__ */ Symbol("PUSH");
15
+ var PUSH_DEVICE_STORE = /* @__PURE__ */ Symbol("PUSH_DEVICE_STORE");
16
+
17
+ // src/push/push.options.ts
18
+ var PUSH_OPTIONS = /* @__PURE__ */ Symbol("PUSH_OPTIONS");
19
+
20
+ // src/push/push.module.ts
21
+ var _common = require('@nestjs/common');
22
+
23
+ // src/push/channels/fcm.channel.ts
24
+ var _fs = require('fs');
25
+ var _jsonwebtoken = require('jsonwebtoken'); var _jsonwebtoken2 = _interopRequireDefault(_jsonwebtoken);
26
+ var FCM_SCOPES = "https://www.googleapis.com/auth/firebase.messaging https://www.googleapis.com/auth/cloud-platform";
27
+ var DEFAULT_TOKEN_URI = "https://oauth2.googleapis.com/token";
28
+ var IID_URL = "https://iid.googleapis.com/iid/v1";
29
+ var STALE_CODES = /* @__PURE__ */ new Set(["UNREGISTERED", "SENDER_ID_MISMATCH"]);
30
+ var FcmChannel = class {
31
+ constructor(options) {
32
+ this.kind = "fcm";
33
+ this.account = parseServiceAccount(options.serviceAccount);
34
+ this.fetchImpl = _nullishCoalesce(options.fetchImpl, () => ( globalThis.fetch));
35
+ }
36
+ get projectId() {
37
+ return this.account.project_id;
38
+ }
39
+ async send(device, message) {
40
+ if (device.kind !== "fcm") return { code: "wrong_channel", message: "Not an FCM device.", stale: false };
41
+ return this.post({ token: device.token }, message);
42
+ }
43
+ async sendToTopic(topic, message) {
44
+ const result = await this.post({ topic }, message);
45
+ if ("code" in result) throw new Error(`FCM topic send failed: ${result.code} ${result.message}`);
46
+ return result;
47
+ }
48
+ async subscribeToTopic(tokens, topic) {
49
+ await this.topicBatch("batchAdd", tokens, topic);
50
+ }
51
+ async unsubscribeFromTopic(tokens, topic) {
52
+ await this.topicBatch("batchRemove", tokens, topic);
53
+ }
54
+ /** The FCM v1 message for a target. Exported through the instance so a test can pin the exact bytes. */
55
+ buildMessage(target, message) {
56
+ return toFcmMessage(target, message);
57
+ }
58
+ async post(target, message, retried = false) {
59
+ const accessToken = await this.accessToken();
60
+ let response;
61
+ try {
62
+ response = await this.fetchImpl(`https://fcm.googleapis.com/v1/projects/${this.account.project_id}/messages:send`, {
63
+ method: "POST",
64
+ headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
65
+ body: JSON.stringify({ message: toFcmMessage(target, message) })
66
+ });
67
+ } catch (cause) {
68
+ return { code: "unreachable", message: cause instanceof Error ? cause.message : String(cause), stale: false };
69
+ }
70
+ const body = await readBody(response);
71
+ if (response.ok) {
72
+ return { id: _nullishCoalesce(_optionalChain([body, 'optionalAccess', _ => _.name]), () => ( null)) };
73
+ }
74
+ if (response.status === 401 && !retried) {
75
+ this.token = void 0;
76
+ return this.post(target, message, true);
77
+ }
78
+ const error = _optionalChain([body, 'optionalAccess', _2 => _2.error]);
79
+ const fcmCode = _optionalChain([error, 'optionalAccess', _3 => _3.details, 'optionalAccess', _4 => _4.find, 'call', _5 => _5((d) => d.errorCode), 'optionalAccess', _6 => _6.errorCode]);
80
+ const code = _nullishCoalesce(_nullishCoalesce(fcmCode, () => ( _optionalChain([error, 'optionalAccess', _7 => _7.status]))), () => ( String(response.status)));
81
+ return {
82
+ code,
83
+ message: _nullishCoalesce(_optionalChain([error, 'optionalAccess', _8 => _8.message]), () => ( `HTTP ${response.status}`)),
84
+ // Only FCM's own verdict counts. A 404 alone, or INVALID_ARGUMENT, can
85
+ // come from a malformed payload — deleting a live token over that
86
+ // loses the device for nothing.
87
+ stale: STALE_CODES.has(code)
88
+ };
89
+ }
90
+ async topicBatch(op, tokens, topic) {
91
+ if (tokens.length === 0) return;
92
+ const accessToken = await this.accessToken();
93
+ const response = await this.fetchImpl(`${IID_URL}:${op}`, {
94
+ method: "POST",
95
+ headers: {
96
+ Authorization: `Bearer ${accessToken}`,
97
+ "Content-Type": "application/json",
98
+ access_token_auth: "true"
99
+ },
100
+ body: JSON.stringify({ to: `/topics/${topic}`, registration_tokens: tokens })
101
+ });
102
+ if (!response.ok) {
103
+ throw new Error(`FCM topic ${op} failed: HTTP ${response.status} ${JSON.stringify(await readBody(response)).slice(0, 200)}`);
104
+ }
105
+ }
106
+ /**
107
+ * The OAuth2 access token, minted from a self-signed JWT and kept until
108
+ * a minute before it expires. Concurrent sends share one in-flight
109
+ * request rather than each minting their own.
110
+ */
111
+ accessToken() {
112
+ if (this.token && this.token.expiresAt - 6e4 > Date.now()) return Promise.resolve(this.token.value);
113
+ this.tokenInFlight ??= this.mintAccessToken().finally(() => {
114
+ this.tokenInFlight = void 0;
115
+ });
116
+ return this.tokenInFlight;
117
+ }
118
+ async mintAccessToken() {
119
+ const tokenUri = _nullishCoalesce(this.account.token_uri, () => ( DEFAULT_TOKEN_URI));
120
+ const assertion = _jsonwebtoken2.default.sign(
121
+ { scope: FCM_SCOPES },
122
+ this.account.private_key,
123
+ { algorithm: "RS256", issuer: this.account.client_email, audience: tokenUri, expiresIn: 3600 }
124
+ );
125
+ const response = await this.fetchImpl(tokenUri, {
126
+ method: "POST",
127
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
128
+ body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion })
129
+ });
130
+ const body = await readBody(response);
131
+ if (!response.ok || !_optionalChain([body, 'optionalAccess', _9 => _9.access_token])) {
132
+ throw new Error(`FCM: could not obtain an access token: ${_nullishCoalesce(_optionalChain([body, 'optionalAccess', _10 => _10.error]), () => ( response.status))} ${_nullishCoalesce(_optionalChain([body, 'optionalAccess', _11 => _11.error_description]), () => ( ""))}`.trim());
133
+ }
134
+ this.token = { value: body.access_token, expiresAt: Date.now() + (_nullishCoalesce(body.expires_in, () => ( 3600))) * 1e3 };
135
+ return body.access_token;
136
+ }
137
+ };
138
+ function parseServiceAccount(input) {
139
+ let account;
140
+ if (typeof input !== "string") {
141
+ account = input;
142
+ } else {
143
+ const trimmed = input.trim();
144
+ const json = trimmed.startsWith("{") ? trimmed : _fs.readFileSync.call(void 0, trimmed, "utf8");
145
+ account = JSON.parse(json);
146
+ }
147
+ for (const field of ["project_id", "client_email", "private_key"]) {
148
+ if (!account[field]) throw new Error(`PushModule: the Firebase service account has no "${field}".`);
149
+ }
150
+ return { ...account, private_key: account.private_key.replace(/\\n/g, "\n") };
151
+ }
152
+ async function readBody(response) {
153
+ const text = await response.text();
154
+ try {
155
+ return text ? JSON.parse(text) : void 0;
156
+ } catch (e) {
157
+ return text;
158
+ }
159
+ }
160
+ function stringifyData(data) {
161
+ const out = {};
162
+ for (const [key, value] of Object.entries(data)) {
163
+ if (value === void 0 || value === null) continue;
164
+ out[key] = typeof value === "string" ? value : JSON.stringify(value);
165
+ }
166
+ return out;
167
+ }
168
+ function toFcmMessage(target, m) {
169
+ const high = m.priority !== "normal";
170
+ const data = stringifyData({
171
+ ...m.data,
172
+ link: m.link,
173
+ actions: _optionalChain([m, 'access', _12 => _12.actions, 'optionalAccess', _13 => _13.length]) ? m.actions : void 0,
174
+ category: m.category,
175
+ ...m.dataOnly ? { title: m.title, body: m.body, imageUrl: m.imageUrl, icon: m.icon, badge: m.badge } : {}
176
+ });
177
+ const message = { ...target, data };
178
+ if (!m.dataOnly) {
179
+ message.notification = compact({ title: m.title, body: m.body, image: m.imageUrl });
180
+ }
181
+ message.android = compact({
182
+ priority: high ? "high" : "normal",
183
+ collapse_key: m.collapseKey,
184
+ ttl: m.ttlSeconds !== void 0 ? `${m.ttlSeconds}s` : void 0,
185
+ notification: m.dataOnly ? void 0 : compact({
186
+ channel_id: m.androidChannelId,
187
+ sound: _nullishCoalesce(m.sound, () => ( "default")),
188
+ image: m.imageUrl,
189
+ notification_count: m.badge
190
+ })
191
+ });
192
+ message.apns = compact({
193
+ headers: compact({
194
+ "apns-push-type": m.dataOnly ? "background" : "alert",
195
+ "apns-priority": m.dataOnly ? "5" : high ? "10" : "5",
196
+ "apns-collapse-id": m.collapseKey,
197
+ "apns-expiration": m.ttlSeconds !== void 0 ? String(Math.floor(Date.now() / 1e3) + m.ttlSeconds) : void 0
198
+ }),
199
+ payload: {
200
+ aps: m.dataOnly ? { "content-available": 1 } : compact({
201
+ sound: _nullishCoalesce(m.sound, () => ( "default")),
202
+ badge: m.badge,
203
+ category: m.category,
204
+ "mutable-content": m.imageUrl ? 1 : void 0
205
+ })
206
+ },
207
+ fcm_options: m.imageUrl && !m.dataOnly ? { image: m.imageUrl } : void 0
208
+ });
209
+ message.webpush = compact({
210
+ headers: compact({
211
+ TTL: m.ttlSeconds !== void 0 ? String(m.ttlSeconds) : void 0,
212
+ Urgency: high ? "high" : "normal"
213
+ }),
214
+ notification: m.dataOnly ? void 0 : compact({
215
+ title: m.title,
216
+ body: m.body,
217
+ icon: m.icon,
218
+ image: m.imageUrl,
219
+ tag: m.collapseKey,
220
+ actions: _optionalChain([m, 'access', _14 => _14.actions, 'optionalAccess', _15 => _15.map, 'call', _16 => _16((a) => compact({ action: a.id, title: a.title, icon: a.icon }))]),
221
+ data: compact({ link: m.link, actions: m.actions })
222
+ }),
223
+ fcm_options: _optionalChain([m, 'access', _17 => _17.link, 'optionalAccess', _18 => _18.startsWith, 'call', _19 => _19("https://")]) && !m.dataOnly ? { link: m.link } : void 0
224
+ });
225
+ return message;
226
+ }
227
+ function compact(object) {
228
+ const out = {};
229
+ for (const [key, value] of Object.entries(object)) {
230
+ if (value === void 0) continue;
231
+ if (typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 0) continue;
232
+ out[key] = value;
233
+ }
234
+ return out;
235
+ }
236
+
237
+ // src/push/channels/webpush.channel.ts
238
+ var WebPushChannel = class {
239
+ constructor(options, lib) {
240
+ this.options = options;
241
+ this.kind = "webpush";
242
+ if (!options.subject || !options.publicKey || !options.privateKey) {
243
+ throw new Error("PushModule: webPush needs subject, publicKey and privateKey (VAPID_SUBJECT, VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY).");
244
+ }
245
+ if (lib) this.libPromise = Promise.resolve(this.configure(lib));
246
+ }
247
+ lib() {
248
+ this.libPromise ??= Promise.resolve().then(() => _interopRequireWildcard(require("web-push"))).then((m) => this.configure(_nullishCoalesce(m.default, () => ( m))));
249
+ return this.libPromise;
250
+ }
251
+ configure(lib) {
252
+ lib.setVapidDetails(this.options.subject, this.options.publicKey, this.options.privateKey);
253
+ return lib;
254
+ }
255
+ /** The JSON the worker gets. On the instance so a test can pin it. */
256
+ buildPayload(message) {
257
+ const payload = { title: message.title, body: message.body };
258
+ if (message.icon) payload.icon = message.icon;
259
+ if (message.imageUrl) payload.image = message.imageUrl;
260
+ if (message.badge !== void 0) payload.badge = message.badge;
261
+ if (message.collapseKey) payload.tag = message.collapseKey;
262
+ if (message.link) payload.link = message.link;
263
+ if (_optionalChain([message, 'access', _20 => _20.actions, 'optionalAccess', _21 => _21.length])) {
264
+ payload.actions = message.actions.map((a) => ({ action: a.id, title: a.title, ...a.icon ? { icon: a.icon } : {}, ...a.link ? { link: a.link } : {} }));
265
+ }
266
+ if (message.data && Object.keys(message.data).length) payload.data = message.data;
267
+ return payload;
268
+ }
269
+ async send(device, message) {
270
+ if (device.kind !== "webpush") return { code: "wrong_channel", message: "Not a Web Push subscription.", stale: false };
271
+ const lib = await this.lib();
272
+ try {
273
+ await lib.sendNotification(
274
+ { endpoint: device.endpoint, keys: device.keys },
275
+ JSON.stringify(this.buildPayload(message)),
276
+ {
277
+ TTL: message.ttlSeconds,
278
+ urgency: message.priority === "normal" ? "normal" : "high",
279
+ topic: message.collapseKey
280
+ }
281
+ );
282
+ return { id: null };
283
+ } catch (cause) {
284
+ const status = cause.statusCode;
285
+ return {
286
+ code: status !== void 0 ? String(status) : "unreachable",
287
+ message: cause instanceof Error ? cause.message : String(cause),
288
+ stale: status === 404 || status === 410
289
+ };
290
+ }
291
+ }
292
+ };
293
+
294
+ // src/push/push.service.ts
295
+
296
+ var PushService = class _PushService {
297
+ constructor(channels, devices, concurrency = 20) {
298
+ this.devices = devices;
299
+ this.concurrency = concurrency;
300
+ this.logger = new (0, _common.Logger)(_PushService.name);
301
+ this.byKind = {};
302
+ for (const channel of channels) this.byKind[channel.kind] = channel;
303
+ }
304
+ channels() {
305
+ return { fcm: Boolean(this.byKind.fcm), webpush: Boolean(this.byKind.webpush) };
306
+ }
307
+ async send(devices, message, options = {}) {
308
+ const list = Array.isArray(devices) ? devices : [devices];
309
+ const resolved = resolveMessage(message, options.lang);
310
+ const result = { sent: 0, failed: [], ids: [] };
311
+ if (list.length === 0) return result;
312
+ const outcomes = await mapLimit(list, this.concurrency, async (device) => {
313
+ const channel = this.byKind[device.kind];
314
+ if (!channel) {
315
+ return { device, code: "channel_not_configured", message: `No ${device.kind} channel is configured.`, stale: false };
316
+ }
317
+ const outcome = await channel.send(device, resolved);
318
+ return "code" in outcome ? { device, ...outcome } : outcome;
319
+ });
320
+ for (const outcome of outcomes) {
321
+ if ("code" in outcome) {
322
+ result.failed.push(outcome);
323
+ result.ids.push(null);
324
+ } else {
325
+ result.sent += 1;
326
+ result.ids.push(outcome.id);
327
+ }
328
+ }
329
+ return result;
330
+ }
331
+ async sendToUser(userId, message, options = {}) {
332
+ if (!this.devices) throw new Error("PushModule: sendToUser needs a PushDeviceStorePort bound to PUSH_DEVICE_STORE.");
333
+ const stored = await this.devices.listByUser(userId);
334
+ const result = await this.send(stored.map((s) => s.device), message, options);
335
+ const dead = stored.filter((s) => result.failed.some((f) => f.stale && f.device === s.device));
336
+ await Promise.all(
337
+ dead.map(
338
+ (s) => this.devices.remove(s.id).catch(
339
+ (error) => this.logger.warn(`Could not remove stale device ${s.id}: ${error instanceof Error ? error.message : String(error)}`)
340
+ )
341
+ )
342
+ );
343
+ return result;
344
+ }
345
+ async sendToTopic(topic, message, options = {}) {
346
+ return this.fcm().sendToTopic(topic, resolveMessage(message, options.lang));
347
+ }
348
+ subscribeToTopic(tokens, topic) {
349
+ return this.fcm().subscribeToTopic(tokens, topic);
350
+ }
351
+ unsubscribeFromTopic(tokens, topic) {
352
+ return this.fcm().unsubscribeFromTopic(tokens, topic);
353
+ }
354
+ fcm() {
355
+ const channel = this.byKind.fcm;
356
+ if (!channel) throw new Error("PushModule: topics need the FCM channel configured.");
357
+ return channel;
358
+ }
359
+ };
360
+ function resolveMessage(message, lang) {
361
+ const text = (value) => _chunkPNK5WMPPcjs.isI18nMessage.call(void 0, value) ? _chunkAXMW5JF7cjs.translate.call(void 0, value, { lang }) : String(value);
362
+ return {
363
+ ...message,
364
+ title: text(message.title),
365
+ body: text(message.body),
366
+ actions: _optionalChain([message, 'access', _22 => _22.actions, 'optionalAccess', _23 => _23.map, 'call', _24 => _24((a) => ({ ...a, title: text(a.title) }))])
367
+ };
368
+ }
369
+ async function mapLimit(items, limit, fn) {
370
+ const results = new Array(items.length);
371
+ let next = 0;
372
+ const worker = async () => {
373
+ while (next < items.length) {
374
+ const index = next++;
375
+ results[index] = await fn(items[index]);
376
+ }
377
+ };
378
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
379
+ return results;
380
+ }
381
+
382
+ // src/push/push.module.ts
383
+ var env = (k) => process.env[k] || void 0;
384
+ function resolvePushOptions(options = {}) {
385
+ const serviceAccount = _nullishCoalesce(_nullishCoalesce(env("FIREBASE_SERVICE_ACCOUNT"), () => ( env("FIREBASE_SERVICE_ACCOUNT_FILE"))), () => ( env("GOOGLE_APPLICATION_CREDENTIALS")));
386
+ const subject = env("VAPID_SUBJECT");
387
+ return {
388
+ fcm: _nullishCoalesce(options.fcm, () => ( (serviceAccount ? { serviceAccount } : void 0))),
389
+ webPush: _nullishCoalesce(options.webPush, () => ( (subject ? { subject, publicKey: _nullishCoalesce(env("VAPID_PUBLIC_KEY"), () => ( "")), privateKey: _nullishCoalesce(env("VAPID_PRIVATE_KEY"), () => ( "")) } : void 0))),
390
+ whenUnconfigured: _nullishCoalesce(options.whenUnconfigured, () => ( "warn"))
391
+ };
392
+ }
393
+ function createPushChannels(options = {}) {
394
+ const resolved = resolvePushOptions(options);
395
+ const channels = [];
396
+ if (resolved.fcm) channels.push(new FcmChannel(resolved.fcm));
397
+ if (resolved.webPush) channels.push(new WebPushChannel(resolved.webPush));
398
+ if (channels.length === 0) {
399
+ const message = "PushModule: no channel configured (fcm / webPush, or FIREBASE_SERVICE_ACCOUNT / VAPID_*). Push is off.";
400
+ if (resolved.whenUnconfigured === "throw") throw new Error(message);
401
+ new (0, _common.Logger)("PushModule").warn(message);
402
+ }
403
+ return channels;
404
+ }
405
+ var PushModule = class {
406
+ static forRoot(options = {}) {
407
+ const { deviceStore, imports, ...pushOptions } = options;
408
+ const providers = [
409
+ { provide: PUSH_OPTIONS, useValue: pushOptions },
410
+ ...deviceStore ? [deviceStore] : [],
411
+ {
412
+ provide: PUSH,
413
+ useFactory: (store) => new PushService(createPushChannels(pushOptions), _nullishCoalesce(store, () => ( void 0))),
414
+ inject: [{ token: PUSH_DEVICE_STORE, optional: true }]
415
+ }
416
+ ];
417
+ return { module: PushModule, imports: _nullishCoalesce(imports, () => ( [])), providers, exports: [PUSH, PUSH_OPTIONS] };
418
+ }
419
+ static forRootAsync(config) {
420
+ const providers = [
421
+ { provide: PUSH_OPTIONS, useFactory: config.useFactory, inject: _nullishCoalesce(config.inject, () => ( [])) },
422
+ ...config.deviceStore ? [config.deviceStore] : [],
423
+ {
424
+ provide: PUSH,
425
+ useFactory: (options, store) => new PushService(createPushChannels(options), _nullishCoalesce(store, () => ( void 0))),
426
+ inject: [PUSH_OPTIONS, { token: PUSH_DEVICE_STORE, optional: true }]
427
+ }
428
+ ];
429
+ return { module: PushModule, imports: _nullishCoalesce(config.imports, () => ( [])), providers, exports: [PUSH, PUSH_OPTIONS] };
430
+ }
431
+ };
432
+ PushModule = exports.PushModule = _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
433
+ _common.Global.call(void 0, ),
434
+ _common.Module.call(void 0, {})
435
+ ], PushModule);
436
+
437
+
438
+
439
+
440
+
441
+
442
+
443
+
444
+
445
+
446
+
447
+
448
+
449
+ exports.FcmChannel = FcmChannel; exports.PUSH = PUSH; exports.PUSH_DEVICE_STORE = PUSH_DEVICE_STORE; exports.PUSH_OPTIONS = PUSH_OPTIONS; exports.PushModule = PushModule; exports.PushService = PushService; exports.WebPushChannel = WebPushChannel; exports.createPushChannels = createPushChannels; exports.parseServiceAccount = parseServiceAccount; exports.resolveMessage = resolveMessage; exports.resolvePushOptions = resolvePushOptions; exports.toFcmMessage = toFcmMessage;
@@ -0,0 +1,9 @@
1
+ export { PUSH, PUSH_DEVICE_STORE } from './push.port.js';
2
+ export type { PushPort, PushDevice, FcmDevice, WebPushDevice, PushMessage, PushAction, PushResult, PushFailure, SendOptions, PushDeviceStorePort, StoredPushDevice, PushChannelPort, ResolvedPushMessage, } from './push.port.js';
3
+ export { PUSH_OPTIONS } from './push.options.js';
4
+ export type { PushOptions, FcmOptions, WebPushOptions, FirebaseServiceAccount } from './push.options.js';
5
+ export { PushModule, createPushChannels, resolvePushOptions } from './push.module.js';
6
+ export { PushService, resolveMessage } from './push.service.js';
7
+ export { FcmChannel, toFcmMessage, parseServiceAccount } from './channels/fcm.channel.js';
8
+ export { WebPushChannel } from './channels/webpush.channel.js';
9
+ export type { WebPushLike, WebPushPayload } from './channels/webpush.channel.js';