@lunora/notify 1.0.0-alpha.112 → 1.0.0-alpha.113
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/LICENSE.md +201 -104
- package/README.md +29 -2
- package/dist/index.d.mts +151 -12
- package/dist/index.d.ts +151 -12
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/buildEngine-DT7F7Xkq.mjs +1 -0
- package/dist/packem_shared/createNotify-DHMOcL17.mjs +1 -0
- package/dist/packem_shared/{d1SubscriptionStore-B13P2ERZ.mjs → d1SubscriptionStore-F2QkHI0n.mjs} +1 -1
- package/dist/packem_shared/{enqueuePushBroadcast-C9tO0BZj.mjs → enqueuePushBroadcast-C4AJpS6v.mjs} +1 -1
- package/dist/packem_shared/{fcmId-o_liCQKp.mjs → fcmId-D3H5mJ9-.mjs} +1 -1
- package/dist/packem_shared/{memorySubscriptionStore-Ccr3ErTV.mjs → memorySubscriptionStore-Pwb6nZpQ.mjs} +1 -1
- package/dist/packem_shared/{normalize-B5B9QUol.mjs → normalize--gkXcjKt.mjs} +1 -1
- package/dist/packem_shared/providers-CZaNFGWC.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/buildEngine-D6jKHClU.mjs +0 -1
- package/dist/packem_shared/createNotify-Bfgf4YrZ.mjs +0 -1
- package/dist/packem_shared/providers-BKnOwMJ6.mjs +0 -1
package/LICENSE.md
CHANGED
|
@@ -1,108 +1,205 @@
|
|
|
1
|
-
# Functional Source License, Version 1.1, Apache 2.0 Future License
|
|
2
1
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
106
203
|
|
|
107
204
|
<!-- DEPENDENCIES -->
|
|
108
205
|
<!-- /DEPENDENCIES -->
|
package/README.md
CHANGED
|
@@ -139,7 +139,7 @@ export const announce = action.input({ title: v.string(), body: v.string() }).ac
|
|
|
139
139
|
});
|
|
140
140
|
```
|
|
141
141
|
|
|
142
|
-
`broadcast` reuses the engine's retry + circuit-breaker middleware and prunes subscriptions the push service reports as gone (Web Push HTTP 404/410; FCM's `
|
|
142
|
+
`broadcast` reuses the engine's retry + circuit-breaker middleware and prunes subscriptions the push service reports as gone (Web Push HTTP 404/410; for an FCM device, only FCM's `UNREGISTERED` code, so a bare `NOT_FOUND` or a message that merely says "not registered" never prunes). A single targeted send:
|
|
143
143
|
|
|
144
144
|
```ts
|
|
145
145
|
await ctx.push.send(subscriptionId, { title: "Hi", body: "…" });
|
|
@@ -151,6 +151,33 @@ await ctx.push.send(subscriptionId, { title: "Hi", body: "…" });
|
|
|
151
151
|
await ctx.push.broadcast({ title: "Approval needed", body: "…", urgency: "high", ttl: 3600 }, { userId });
|
|
152
152
|
```
|
|
153
153
|
|
|
154
|
+
FCM-specific fields go in `fcmOverrides`, which is forwarded to the message as sent, per platform. It is merged over what the common fields produce, so it wins on a clash. Web Push ignores it:
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
await ctx.push.broadcast(
|
|
158
|
+
{
|
|
159
|
+
title: "Kickoff",
|
|
160
|
+
body: "Match starts now",
|
|
161
|
+
clickAction: "OPEN_MATCH", // android.notification.click_action
|
|
162
|
+
sound: "goal.caf", // android and apns sound
|
|
163
|
+
badge: 3, // apns badge
|
|
164
|
+
fcmOverrides: {
|
|
165
|
+
android: { notification: { channel_id: "live-scores" } },
|
|
166
|
+
apns: { payload: { aps: { category: "MATCH" } } },
|
|
167
|
+
webpush: { fcm_options: { link: "https://example.com/m/42" } },
|
|
168
|
+
},
|
|
169
|
+
},
|
|
170
|
+
{ userId },
|
|
171
|
+
);
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Topics and conditions send one FCM message to every device subscribed to a topic, or matching a condition expression. Lunora does not add or remove devices from topics: subscribe them with the Firebase client SDK or the Admin API. These sends have no subscription rows, so there is no per-device receipt and nothing to prune. They resolve to a success receipt whose `messageId` is the FCM message name, and a failure throws. They need the `fcm` channel:
|
|
175
|
+
|
|
176
|
+
```ts
|
|
177
|
+
await ctx.push.sendToTopic("news", { title: "Breaking", body: "…" });
|
|
178
|
+
await ctx.push.sendToCondition("'sports' in topics && 'news' in topics", { body: "…" });
|
|
179
|
+
```
|
|
180
|
+
|
|
154
181
|
Multi-channel through `ctx.notify.send`:
|
|
155
182
|
|
|
156
183
|
```ts
|
|
@@ -239,7 +266,7 @@ client-supplied data, so the facade enforces two boundaries:
|
|
|
239
266
|
|
|
240
267
|
Every send is counted onto `ctx.metrics` and failures onto `ctx.log` for you — codegen threads the request's logger/metrics into `ctx.notify` (`createNotify(notifyConfig, env, { log, metrics })`), so there is nothing to wire. Two low-cardinality metric series feed the durable metric history + trend charts:
|
|
241
268
|
|
|
242
|
-
- **`notify.send`** `{ channel, provider, status }` — attempted sends. `status` is `accepted` (the provider took it), `failed`, or `gone` (endpoint unregistered — Web Push 404/410, or FCM's `
|
|
269
|
+
- **`notify.send`** `{ channel, provider, status }` — attempted sends. `status` is `accepted` (the provider took it), `failed`, or `gone` (endpoint unregistered — Web Push 404/410, or FCM's `UNREGISTERED` for a dead token — and pruned). A single send counts 1; a **broadcast aggregates** into one count per `(provider, status)` bucket (value = the bucket's count), not one per recipient — each `ctx.metrics.count` is a durable write.
|
|
243
270
|
- **`notify.skipped`** `{ channel, reason }` — a send that reached nobody: `no-subscriptions-matched` (empty broadcast) or `channel-not-configured`.
|
|
244
271
|
|
|
245
272
|
A **failed** send also emits one `ctx.log.warn` line carrying the error and, for push, the subscription/user ids — trace-correlated to the enclosing action and durably archived. Successes and prunes stay off the log; failure logs stay per-recipient even in a broadcast (they have no durable write).
|
package/dist/index.d.mts
CHANGED
|
@@ -20,8 +20,120 @@ import { FcmConfig } from '@visulima/notification/providers/fcm';
|
|
|
20
20
|
export type { FcmConfig } from '@visulima/notification/providers/fcm';
|
|
21
21
|
import { PushSubscriptionLike, WebPushConfig } from '@visulima/notification/providers/web-push';
|
|
22
22
|
export type { PushSubscriptionLike, WebPushConfig } from '@visulima/notification/providers/web-push';
|
|
23
|
-
import { ChatPayload, Receipt, InAppPayload,
|
|
24
|
-
export type { ChatPayload, InAppPayload,
|
|
23
|
+
import { PushPayload, Provider, ChatPayload, Receipt, InAppPayload, SuccessReceipt, NotificationMessage as NotificationMessage$1, WebhookPayload, Notification } from '@visulima/notification';
|
|
24
|
+
export type { ChatPayload, InAppPayload, PushPayload, Receipt, WebhookPayload } from '@visulima/notification';
|
|
25
|
+
/**
|
|
26
|
+
* The per-platform blocks of an FCM HTTP v1 message, forwarded as sent. Only the
|
|
27
|
+
* fields a push app reaches for are typed; a field not listed here is a type error
|
|
28
|
+
* rather than being silently dropped, so a typo cannot reach the wire unnoticed.
|
|
29
|
+
*/
|
|
30
|
+
interface FcmAndroidConfig {
|
|
31
|
+
collapse_key?: string;
|
|
32
|
+
data?: Record<string, string>;
|
|
33
|
+
fcm_options?: {
|
|
34
|
+
analytics_label?: string;
|
|
35
|
+
};
|
|
36
|
+
notification?: {
|
|
37
|
+
body?: string;
|
|
38
|
+
channel_id?: string;
|
|
39
|
+
click_action?: string;
|
|
40
|
+
color?: string;
|
|
41
|
+
icon?: string;
|
|
42
|
+
image?: string;
|
|
43
|
+
sound?: string;
|
|
44
|
+
tag?: string;
|
|
45
|
+
title?: string;
|
|
46
|
+
};
|
|
47
|
+
/** FCM HTTP v1 takes the uppercase enum values. */
|
|
48
|
+
priority?: "HIGH" | "NORMAL";
|
|
49
|
+
ttl?: string;
|
|
50
|
+
}
|
|
51
|
+
interface FcmApnsConfig {
|
|
52
|
+
fcm_options?: {
|
|
53
|
+
analytics_label?: string;
|
|
54
|
+
image?: string;
|
|
55
|
+
};
|
|
56
|
+
headers?: Record<string, string>;
|
|
57
|
+
payload?: {
|
|
58
|
+
[key: string]: unknown;
|
|
59
|
+
aps?: {
|
|
60
|
+
alert?: {
|
|
61
|
+
body?: string;
|
|
62
|
+
subtitle?: string;
|
|
63
|
+
title?: string;
|
|
64
|
+
};
|
|
65
|
+
badge?: number;
|
|
66
|
+
category?: string;
|
|
67
|
+
"content-available"?: 0 | 1;
|
|
68
|
+
"interruption-level"?: "passive" | "active" | "time-sensitive" | "critical";
|
|
69
|
+
"mutable-content"?: 0 | 1;
|
|
70
|
+
sound?: string | {
|
|
71
|
+
critical?: 0 | 1;
|
|
72
|
+
name?: string;
|
|
73
|
+
volume?: number;
|
|
74
|
+
};
|
|
75
|
+
"thread-id"?: string;
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
interface FcmWebpushConfig {
|
|
80
|
+
data?: Record<string, string>;
|
|
81
|
+
fcm_options?: {
|
|
82
|
+
analytics_label?: string;
|
|
83
|
+
link?: string;
|
|
84
|
+
};
|
|
85
|
+
headers?: Record<string, string>;
|
|
86
|
+
notification?: {
|
|
87
|
+
actions?: ReadonlyArray<{
|
|
88
|
+
action: string;
|
|
89
|
+
icon?: string;
|
|
90
|
+
title: string;
|
|
91
|
+
}>;
|
|
92
|
+
badge?: string;
|
|
93
|
+
body?: string;
|
|
94
|
+
dir?: "auto" | "ltr" | "rtl";
|
|
95
|
+
icon?: string;
|
|
96
|
+
image?: string;
|
|
97
|
+
lang?: string;
|
|
98
|
+
renotify?: boolean;
|
|
99
|
+
requireInteraction?: boolean;
|
|
100
|
+
silent?: boolean;
|
|
101
|
+
tag?: string;
|
|
102
|
+
title?: string;
|
|
103
|
+
vibrate?: number[];
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/** Per-platform overrides for a push send. `ctx.push.*` takes them as `fcmOverrides`. */
|
|
107
|
+
interface FcmPlatformConfig {
|
|
108
|
+
android?: FcmAndroidConfig;
|
|
109
|
+
apns?: FcmApnsConfig;
|
|
110
|
+
fcm_options?: {
|
|
111
|
+
analytics_label?: string;
|
|
112
|
+
};
|
|
113
|
+
webpush?: FcmWebpushConfig;
|
|
114
|
+
}
|
|
115
|
+
/** A push payload as the FCM transport reads it: the content plus optional per-platform overrides. */
|
|
116
|
+
type FcmPayload = Omit<PushPayload, "to"> & {
|
|
117
|
+
fcmOverrides?: FcmPlatformConfig;
|
|
118
|
+
};
|
|
119
|
+
/** A message addressed to a device token, a topic, or a condition expression. */
|
|
120
|
+
type FcmTarget = {
|
|
121
|
+
condition: string;
|
|
122
|
+
} | {
|
|
123
|
+
token: string;
|
|
124
|
+
} | {
|
|
125
|
+
topic: string;
|
|
126
|
+
};
|
|
127
|
+
interface FcmTransport {
|
|
128
|
+
/** The engine-facing provider: delivers to each token in `to`. Topic and condition go through {@link FcmTransport.sendTo}. */
|
|
129
|
+
provider: Provider<unknown, FcmPayload & {
|
|
130
|
+
to: string | string[];
|
|
131
|
+
}>;
|
|
132
|
+
/** Send one message to a topic or condition. Resolves to the FCM message name. */
|
|
133
|
+
sendTo: (target: Exclude<FcmTarget, {
|
|
134
|
+
token: string;
|
|
135
|
+
}>, payload: FcmPayload) => Promise<string>;
|
|
136
|
+
}
|
|
25
137
|
/**
|
|
26
138
|
* A Worker `env` projected as a plain record (vars, secrets and bindings are
|
|
27
139
|
* `unknown`-valued). `defineNotify` factories receive this so a config can read
|
|
@@ -278,7 +390,7 @@ interface BroadcastPageResult {
|
|
|
278
390
|
*
|
|
279
391
|
* - `accepted` — the provider took the message (a `Receipt.successful` send).
|
|
280
392
|
* - `failed` — a provider error; the log line carries the `error` text.
|
|
281
|
-
* - `gone` — the endpoint is unregistered (Web Push 404/410, FCM's `
|
|
393
|
+
* - `gone` — the endpoint is unregistered (Web Push 404/410, FCM's `UNREGISTERED` for a dead token) and pruned; push-only.
|
|
282
394
|
*
|
|
283
395
|
* Web Push and FCM give no delivery/open receipts, so the vocabulary stops at the
|
|
284
396
|
* send attempt: a `delivered`/`opened` status would be a lie for these channels.
|
|
@@ -323,7 +435,7 @@ interface LunoraPush {
|
|
|
323
435
|
/**
|
|
324
436
|
* Fan-out a push to every stored subscription matching `filter` (default: all).
|
|
325
437
|
* Reuses the engine's retry/circuit-breaker middleware; prunes subscriptions
|
|
326
|
-
* the push service reports as gone (Web Push 404/410, FCM's `
|
|
438
|
+
* the push service reports as gone (Web Push 404/410, FCM's `UNREGISTERED` for a dead token). The `to`
|
|
327
439
|
* target is derived from each subscription, so it is omitted from the payload.
|
|
328
440
|
*
|
|
329
441
|
* Internally walks the audience in bounded pages (via {@link LunoraPush.broadcastPage},
|
|
@@ -376,6 +488,19 @@ interface LunoraPush {
|
|
|
376
488
|
register: (input: RegisterInput) => Promise<StoredSubscription>;
|
|
377
489
|
/** Send a push to a single stored subscription (by id or record); `to` is derived from it. */
|
|
378
490
|
send: (target: StoredSubscription | string, payload: PushContent) => Promise<Receipt>;
|
|
491
|
+
/**
|
|
492
|
+
* Send one message to every device whose topics match an FCM condition, such as
|
|
493
|
+
* `"'sports' in topics && 'news' in topics"`. Same contract as
|
|
494
|
+
* {@link LunoraPush.sendToTopic}.
|
|
495
|
+
*/
|
|
496
|
+
sendToCondition: (condition: string, payload: PushContent) => Promise<SuccessReceipt>;
|
|
497
|
+
/**
|
|
498
|
+
* Send one message to every device subscribed to an FCM topic. Topics have no
|
|
499
|
+
* subscription rows, so there is no per-recipient receipt and no gone-pruning:
|
|
500
|
+
* the result is a success receipt whose `messageId` is the FCM message name, and a failure throws. Requires `fcm` in
|
|
501
|
+
* `defineNotify`; web push has no topics.
|
|
502
|
+
*/
|
|
503
|
+
sendToTopic: (topic: string, payload: PushContent) => Promise<SuccessReceipt>;
|
|
379
504
|
/**
|
|
380
505
|
* Remove ONE of `owner`'s subscriptions by id (idempotent).
|
|
381
506
|
*
|
|
@@ -413,7 +538,14 @@ interface PushOwner {
|
|
|
413
538
|
* stored subscription. Its `ttl` / `urgency` override the channel defaults per
|
|
414
539
|
* message on every push transport (Web Push, FCM, APNs, Expo).
|
|
415
540
|
*/
|
|
416
|
-
type PushContent = Omit<PushPayload, "to"
|
|
541
|
+
type PushContent = Omit<PushPayload, "to"> & {
|
|
542
|
+
/**
|
|
543
|
+
* FCM per-platform overrides (`android`, `apns`, `webpush`, `fcm_options`),
|
|
544
|
+
* forwarded to the message as sent. Applied over the common fields, so an
|
|
545
|
+
* `android.notification.channel_id` here wins over anything derived from them.
|
|
546
|
+
*/
|
|
547
|
+
fcmOverrides?: FcmPlatformConfig;
|
|
548
|
+
};
|
|
417
549
|
/**
|
|
418
550
|
* The multi-channel notification facade — spliced onto ctx as `ctx.notify`.
|
|
419
551
|
* `send` delivers a fully-specified multi-channel message through the engine;
|
|
@@ -506,6 +638,14 @@ interface NotifyDefinition extends NotifyConfig {
|
|
|
506
638
|
/** Runtime brand used by `isNotifyDefinition` and codegen discovery. */
|
|
507
639
|
readonly isLunoraNotify: true;
|
|
508
640
|
}
|
|
641
|
+
/** A push payload that may carry FCM per-platform overrides. The overrides reach only FCM targets. */
|
|
642
|
+
type PushMessage = PushPayload & {
|
|
643
|
+
fcmOverrides?: FcmPlatformConfig;
|
|
644
|
+
};
|
|
645
|
+
/** A multi-channel message whose `push` entry accepts `fcmOverrides`. */
|
|
646
|
+
type NotificationMessage = Omit<NotificationMessage$1, "push"> & {
|
|
647
|
+
push?: PushMessage;
|
|
648
|
+
};
|
|
509
649
|
/**
|
|
510
650
|
* `.dev.vars` / Worker `env` keys the built-in config resolvers read. Mirrored in
|
|
511
651
|
* `@lunora/config`'s package-secrets registry so `lunora dev` scaffolds them into
|
|
@@ -672,7 +812,7 @@ interface ResolvedProviders {
|
|
|
672
812
|
* are wired (Web Push, FCM, chat, in-app, webhook); APNs and SMS are excluded
|
|
673
813
|
* from the edge facade by construction.
|
|
674
814
|
*/
|
|
675
|
-
declare const buildEngine: (resolved: ResolvedProviders) => Notification;
|
|
815
|
+
declare const buildEngine: (resolved: ResolvedProviders, fcmTransport?: FcmTransport) => Notification;
|
|
676
816
|
/**
|
|
677
817
|
* A broadcast job body — the JSON-serialisable payload enqueued for off-request
|
|
678
818
|
* fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
|
|
@@ -813,7 +953,7 @@ declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBro
|
|
|
813
953
|
* receipt, or an id whose row no longer exists at all — counts as `pruned` here
|
|
814
954
|
* too, never as a failure: there is nothing left to redeliver to, so retrying it
|
|
815
955
|
* could only burn the queue's budget and dead-letter an unsubscribe.
|
|
816
|
-
* - Gone subscriptions (Web Push 404/410, FCM's `
|
|
956
|
+
* - Gone subscriptions (Web Push 404/410, FCM's `UNREGISTERED` for a dead token) are pruned by the page and
|
|
817
957
|
* never appear in `failedIds` — an all-`pruned` page is a success, not a
|
|
818
958
|
* failure, as is an empty page.
|
|
819
959
|
*/
|
|
@@ -911,10 +1051,9 @@ declare const targetOf: (subscription: StoredSubscription) => string;
|
|
|
911
1051
|
* transient failure worth retrying.
|
|
912
1052
|
*
|
|
913
1053
|
* Gates on STRUCTURED signals first: an `HTTP 404/410` status (both providers
|
|
914
|
-
* answer one for a dead endpoint/token
|
|
915
|
-
*
|
|
916
|
-
* `UNREGISTERED`/`NOT_REGISTERED`
|
|
917
|
-
* signal its provider actually forwards (see {@link FCM_GONE_PATTERN}). The
|
|
1054
|
+
* answer one for a dead endpoint/token). For a known FCM device the signal is only the
|
|
1055
|
+
* dead-token report `FCM 404 UNREGISTERED` (see {@link FCM_DEAD_TOKEN_REPORT}); for a caller with
|
|
1056
|
+
* no kind, the `UNREGISTERED`/`NOT_REGISTERED` codes (see {@link FCM_GONE_PATTERN}) also count. The
|
|
918
1057
|
* free-text {@link GONE_TEXT_FALLBACK} is a tightened last resort only, so a
|
|
919
1058
|
* transient error that happens to contain `expired` (a cert/session expiry) can
|
|
920
1059
|
* never permanently drop a valid subscription.
|
|
@@ -946,7 +1085,7 @@ export { type BroadcastOutcome, type BroadcastResult, type CreateNotifyOptions,
|
|
|
946
1085
|
* - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
|
|
947
1086
|
* @packageDocumentation
|
|
948
1087
|
*/
|
|
949
|
-
FCM_ENV_KEYS, type FcmConfigFactory, type LunoraNotify, type LunoraPush, type NotifyConfig, type NotifyDefinition, type NotifyDeliveryStatus, type NotifyEnv, type NotifyLogger, type NotifyMetrics, type NotifySkipReason, type PushBroadcastJob, type PushBroadcastPageOutcome, type PushOwner, type PushSubscriptionDevice, type PushSubscriptionsResult, type QueueProducerLike, type RegisterInput, type ResolvedProviders, type RoutingPushOptions, type StoredSubscription, type SubscriptionFilter, type SubscriptionKind, type SubscriptionOutcomes, type SubscriptionStatus, type SubscriptionStore,
|
|
1088
|
+
FCM_ENV_KEYS, type FcmAndroidConfig, type FcmApnsConfig, type FcmConfigFactory, type FcmPlatformConfig, type FcmWebpushConfig, type LunoraNotify, type LunoraPush, type NotificationMessage, type NotifyConfig, type NotifyDefinition, type NotifyDeliveryStatus, type NotifyEnv, type NotifyLogger, type NotifyMetrics, type NotifySkipReason, type PushBroadcastJob, type PushBroadcastPageOutcome, type PushOwner, type PushSubscriptionDevice, type PushSubscriptionsResult, type QueueProducerLike, type RegisterInput, type ResolvedProviders, type RoutingPushOptions, type StoredSubscription, type SubscriptionFilter, type SubscriptionKind, type SubscriptionOutcomes, type SubscriptionStatus, type SubscriptionStore,
|
|
950
1089
|
/**
|
|
951
1090
|
* `@lunora/notify`
|
|
952
1091
|
*
|
package/dist/index.d.ts
CHANGED
|
@@ -20,8 +20,120 @@ import { FcmConfig } from '@visulima/notification/providers/fcm';
|
|
|
20
20
|
export type { FcmConfig } from '@visulima/notification/providers/fcm';
|
|
21
21
|
import { PushSubscriptionLike, WebPushConfig } from '@visulima/notification/providers/web-push';
|
|
22
22
|
export type { PushSubscriptionLike, WebPushConfig } from '@visulima/notification/providers/web-push';
|
|
23
|
-
import { ChatPayload, Receipt, InAppPayload,
|
|
24
|
-
export type { ChatPayload, InAppPayload,
|
|
23
|
+
import { PushPayload, Provider, ChatPayload, Receipt, InAppPayload, SuccessReceipt, NotificationMessage as NotificationMessage$1, WebhookPayload, Notification } from '@visulima/notification';
|
|
24
|
+
export type { ChatPayload, InAppPayload, PushPayload, Receipt, WebhookPayload } from '@visulima/notification';
|
|
25
|
+
/**
|
|
26
|
+
* The per-platform blocks of an FCM HTTP v1 message, forwarded as sent. Only the
|
|
27
|
+
* fields a push app reaches for are typed; a field not listed here is a type error
|
|
28
|
+
* rather than being silently dropped, so a typo cannot reach the wire unnoticed.
|
|
29
|
+
*/
|
|
30
|
+
interface FcmAndroidConfig {
|
|
31
|
+
collapse_key?: string;
|
|
32
|
+
data?: Record<string, string>;
|
|
33
|
+
fcm_options?: {
|
|
34
|
+
analytics_label?: string;
|
|
35
|
+
};
|
|
36
|
+
notification?: {
|
|
37
|
+
body?: string;
|
|
38
|
+
channel_id?: string;
|
|
39
|
+
click_action?: string;
|
|
40
|
+
color?: string;
|
|
41
|
+
icon?: string;
|
|
42
|
+
image?: string;
|
|
43
|
+
sound?: string;
|
|
44
|
+
tag?: string;
|
|
45
|
+
title?: string;
|
|
46
|
+
};
|
|
47
|
+
/** FCM HTTP v1 takes the uppercase enum values. */
|
|
48
|
+
priority?: "HIGH" | "NORMAL";
|
|
49
|
+
ttl?: string;
|
|
50
|
+
}
|
|
51
|
+
interface FcmApnsConfig {
|
|
52
|
+
fcm_options?: {
|
|
53
|
+
analytics_label?: string;
|
|
54
|
+
image?: string;
|
|
55
|
+
};
|
|
56
|
+
headers?: Record<string, string>;
|
|
57
|
+
payload?: {
|
|
58
|
+
[key: string]: unknown;
|
|
59
|
+
aps?: {
|
|
60
|
+
alert?: {
|
|
61
|
+
body?: string;
|
|
62
|
+
subtitle?: string;
|
|
63
|
+
title?: string;
|
|
64
|
+
};
|
|
65
|
+
badge?: number;
|
|
66
|
+
category?: string;
|
|
67
|
+
"content-available"?: 0 | 1;
|
|
68
|
+
"interruption-level"?: "passive" | "active" | "time-sensitive" | "critical";
|
|
69
|
+
"mutable-content"?: 0 | 1;
|
|
70
|
+
sound?: string | {
|
|
71
|
+
critical?: 0 | 1;
|
|
72
|
+
name?: string;
|
|
73
|
+
volume?: number;
|
|
74
|
+
};
|
|
75
|
+
"thread-id"?: string;
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
interface FcmWebpushConfig {
|
|
80
|
+
data?: Record<string, string>;
|
|
81
|
+
fcm_options?: {
|
|
82
|
+
analytics_label?: string;
|
|
83
|
+
link?: string;
|
|
84
|
+
};
|
|
85
|
+
headers?: Record<string, string>;
|
|
86
|
+
notification?: {
|
|
87
|
+
actions?: ReadonlyArray<{
|
|
88
|
+
action: string;
|
|
89
|
+
icon?: string;
|
|
90
|
+
title: string;
|
|
91
|
+
}>;
|
|
92
|
+
badge?: string;
|
|
93
|
+
body?: string;
|
|
94
|
+
dir?: "auto" | "ltr" | "rtl";
|
|
95
|
+
icon?: string;
|
|
96
|
+
image?: string;
|
|
97
|
+
lang?: string;
|
|
98
|
+
renotify?: boolean;
|
|
99
|
+
requireInteraction?: boolean;
|
|
100
|
+
silent?: boolean;
|
|
101
|
+
tag?: string;
|
|
102
|
+
title?: string;
|
|
103
|
+
vibrate?: number[];
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/** Per-platform overrides for a push send. `ctx.push.*` takes them as `fcmOverrides`. */
|
|
107
|
+
interface FcmPlatformConfig {
|
|
108
|
+
android?: FcmAndroidConfig;
|
|
109
|
+
apns?: FcmApnsConfig;
|
|
110
|
+
fcm_options?: {
|
|
111
|
+
analytics_label?: string;
|
|
112
|
+
};
|
|
113
|
+
webpush?: FcmWebpushConfig;
|
|
114
|
+
}
|
|
115
|
+
/** A push payload as the FCM transport reads it: the content plus optional per-platform overrides. */
|
|
116
|
+
type FcmPayload = Omit<PushPayload, "to"> & {
|
|
117
|
+
fcmOverrides?: FcmPlatformConfig;
|
|
118
|
+
};
|
|
119
|
+
/** A message addressed to a device token, a topic, or a condition expression. */
|
|
120
|
+
type FcmTarget = {
|
|
121
|
+
condition: string;
|
|
122
|
+
} | {
|
|
123
|
+
token: string;
|
|
124
|
+
} | {
|
|
125
|
+
topic: string;
|
|
126
|
+
};
|
|
127
|
+
interface FcmTransport {
|
|
128
|
+
/** The engine-facing provider: delivers to each token in `to`. Topic and condition go through {@link FcmTransport.sendTo}. */
|
|
129
|
+
provider: Provider<unknown, FcmPayload & {
|
|
130
|
+
to: string | string[];
|
|
131
|
+
}>;
|
|
132
|
+
/** Send one message to a topic or condition. Resolves to the FCM message name. */
|
|
133
|
+
sendTo: (target: Exclude<FcmTarget, {
|
|
134
|
+
token: string;
|
|
135
|
+
}>, payload: FcmPayload) => Promise<string>;
|
|
136
|
+
}
|
|
25
137
|
/**
|
|
26
138
|
* A Worker `env` projected as a plain record (vars, secrets and bindings are
|
|
27
139
|
* `unknown`-valued). `defineNotify` factories receive this so a config can read
|
|
@@ -278,7 +390,7 @@ interface BroadcastPageResult {
|
|
|
278
390
|
*
|
|
279
391
|
* - `accepted` — the provider took the message (a `Receipt.successful` send).
|
|
280
392
|
* - `failed` — a provider error; the log line carries the `error` text.
|
|
281
|
-
* - `gone` — the endpoint is unregistered (Web Push 404/410, FCM's `
|
|
393
|
+
* - `gone` — the endpoint is unregistered (Web Push 404/410, FCM's `UNREGISTERED` for a dead token) and pruned; push-only.
|
|
282
394
|
*
|
|
283
395
|
* Web Push and FCM give no delivery/open receipts, so the vocabulary stops at the
|
|
284
396
|
* send attempt: a `delivered`/`opened` status would be a lie for these channels.
|
|
@@ -323,7 +435,7 @@ interface LunoraPush {
|
|
|
323
435
|
/**
|
|
324
436
|
* Fan-out a push to every stored subscription matching `filter` (default: all).
|
|
325
437
|
* Reuses the engine's retry/circuit-breaker middleware; prunes subscriptions
|
|
326
|
-
* the push service reports as gone (Web Push 404/410, FCM's `
|
|
438
|
+
* the push service reports as gone (Web Push 404/410, FCM's `UNREGISTERED` for a dead token). The `to`
|
|
327
439
|
* target is derived from each subscription, so it is omitted from the payload.
|
|
328
440
|
*
|
|
329
441
|
* Internally walks the audience in bounded pages (via {@link LunoraPush.broadcastPage},
|
|
@@ -376,6 +488,19 @@ interface LunoraPush {
|
|
|
376
488
|
register: (input: RegisterInput) => Promise<StoredSubscription>;
|
|
377
489
|
/** Send a push to a single stored subscription (by id or record); `to` is derived from it. */
|
|
378
490
|
send: (target: StoredSubscription | string, payload: PushContent) => Promise<Receipt>;
|
|
491
|
+
/**
|
|
492
|
+
* Send one message to every device whose topics match an FCM condition, such as
|
|
493
|
+
* `"'sports' in topics && 'news' in topics"`. Same contract as
|
|
494
|
+
* {@link LunoraPush.sendToTopic}.
|
|
495
|
+
*/
|
|
496
|
+
sendToCondition: (condition: string, payload: PushContent) => Promise<SuccessReceipt>;
|
|
497
|
+
/**
|
|
498
|
+
* Send one message to every device subscribed to an FCM topic. Topics have no
|
|
499
|
+
* subscription rows, so there is no per-recipient receipt and no gone-pruning:
|
|
500
|
+
* the result is a success receipt whose `messageId` is the FCM message name, and a failure throws. Requires `fcm` in
|
|
501
|
+
* `defineNotify`; web push has no topics.
|
|
502
|
+
*/
|
|
503
|
+
sendToTopic: (topic: string, payload: PushContent) => Promise<SuccessReceipt>;
|
|
379
504
|
/**
|
|
380
505
|
* Remove ONE of `owner`'s subscriptions by id (idempotent).
|
|
381
506
|
*
|
|
@@ -413,7 +538,14 @@ interface PushOwner {
|
|
|
413
538
|
* stored subscription. Its `ttl` / `urgency` override the channel defaults per
|
|
414
539
|
* message on every push transport (Web Push, FCM, APNs, Expo).
|
|
415
540
|
*/
|
|
416
|
-
type PushContent = Omit<PushPayload, "to"
|
|
541
|
+
type PushContent = Omit<PushPayload, "to"> & {
|
|
542
|
+
/**
|
|
543
|
+
* FCM per-platform overrides (`android`, `apns`, `webpush`, `fcm_options`),
|
|
544
|
+
* forwarded to the message as sent. Applied over the common fields, so an
|
|
545
|
+
* `android.notification.channel_id` here wins over anything derived from them.
|
|
546
|
+
*/
|
|
547
|
+
fcmOverrides?: FcmPlatformConfig;
|
|
548
|
+
};
|
|
417
549
|
/**
|
|
418
550
|
* The multi-channel notification facade — spliced onto ctx as `ctx.notify`.
|
|
419
551
|
* `send` delivers a fully-specified multi-channel message through the engine;
|
|
@@ -506,6 +638,14 @@ interface NotifyDefinition extends NotifyConfig {
|
|
|
506
638
|
/** Runtime brand used by `isNotifyDefinition` and codegen discovery. */
|
|
507
639
|
readonly isLunoraNotify: true;
|
|
508
640
|
}
|
|
641
|
+
/** A push payload that may carry FCM per-platform overrides. The overrides reach only FCM targets. */
|
|
642
|
+
type PushMessage = PushPayload & {
|
|
643
|
+
fcmOverrides?: FcmPlatformConfig;
|
|
644
|
+
};
|
|
645
|
+
/** A multi-channel message whose `push` entry accepts `fcmOverrides`. */
|
|
646
|
+
type NotificationMessage = Omit<NotificationMessage$1, "push"> & {
|
|
647
|
+
push?: PushMessage;
|
|
648
|
+
};
|
|
509
649
|
/**
|
|
510
650
|
* `.dev.vars` / Worker `env` keys the built-in config resolvers read. Mirrored in
|
|
511
651
|
* `@lunora/config`'s package-secrets registry so `lunora dev` scaffolds them into
|
|
@@ -672,7 +812,7 @@ interface ResolvedProviders {
|
|
|
672
812
|
* are wired (Web Push, FCM, chat, in-app, webhook); APNs and SMS are excluded
|
|
673
813
|
* from the edge facade by construction.
|
|
674
814
|
*/
|
|
675
|
-
declare const buildEngine: (resolved: ResolvedProviders) => Notification;
|
|
815
|
+
declare const buildEngine: (resolved: ResolvedProviders, fcmTransport?: FcmTransport) => Notification;
|
|
676
816
|
/**
|
|
677
817
|
* A broadcast job body — the JSON-serialisable payload enqueued for off-request
|
|
678
818
|
* fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
|
|
@@ -813,7 +953,7 @@ declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBro
|
|
|
813
953
|
* receipt, or an id whose row no longer exists at all — counts as `pruned` here
|
|
814
954
|
* too, never as a failure: there is nothing left to redeliver to, so retrying it
|
|
815
955
|
* could only burn the queue's budget and dead-letter an unsubscribe.
|
|
816
|
-
* - Gone subscriptions (Web Push 404/410, FCM's `
|
|
956
|
+
* - Gone subscriptions (Web Push 404/410, FCM's `UNREGISTERED` for a dead token) are pruned by the page and
|
|
817
957
|
* never appear in `failedIds` — an all-`pruned` page is a success, not a
|
|
818
958
|
* failure, as is an empty page.
|
|
819
959
|
*/
|
|
@@ -911,10 +1051,9 @@ declare const targetOf: (subscription: StoredSubscription) => string;
|
|
|
911
1051
|
* transient failure worth retrying.
|
|
912
1052
|
*
|
|
913
1053
|
* Gates on STRUCTURED signals first: an `HTTP 404/410` status (both providers
|
|
914
|
-
* answer one for a dead endpoint/token
|
|
915
|
-
*
|
|
916
|
-
* `UNREGISTERED`/`NOT_REGISTERED`
|
|
917
|
-
* signal its provider actually forwards (see {@link FCM_GONE_PATTERN}). The
|
|
1054
|
+
* answer one for a dead endpoint/token). For a known FCM device the signal is only the
|
|
1055
|
+
* dead-token report `FCM 404 UNREGISTERED` (see {@link FCM_DEAD_TOKEN_REPORT}); for a caller with
|
|
1056
|
+
* no kind, the `UNREGISTERED`/`NOT_REGISTERED` codes (see {@link FCM_GONE_PATTERN}) also count. The
|
|
918
1057
|
* free-text {@link GONE_TEXT_FALLBACK} is a tightened last resort only, so a
|
|
919
1058
|
* transient error that happens to contain `expired` (a cert/session expiry) can
|
|
920
1059
|
* never permanently drop a valid subscription.
|
|
@@ -946,7 +1085,7 @@ export { type BroadcastOutcome, type BroadcastResult, type CreateNotifyOptions,
|
|
|
946
1085
|
* - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
|
|
947
1086
|
* @packageDocumentation
|
|
948
1087
|
*/
|
|
949
|
-
FCM_ENV_KEYS, type FcmConfigFactory, type LunoraNotify, type LunoraPush, type NotifyConfig, type NotifyDefinition, type NotifyDeliveryStatus, type NotifyEnv, type NotifyLogger, type NotifyMetrics, type NotifySkipReason, type PushBroadcastJob, type PushBroadcastPageOutcome, type PushOwner, type PushSubscriptionDevice, type PushSubscriptionsResult, type QueueProducerLike, type RegisterInput, type ResolvedProviders, type RoutingPushOptions, type StoredSubscription, type SubscriptionFilter, type SubscriptionKind, type SubscriptionOutcomes, type SubscriptionStatus, type SubscriptionStore,
|
|
1088
|
+
FCM_ENV_KEYS, type FcmAndroidConfig, type FcmApnsConfig, type FcmConfigFactory, type FcmPlatformConfig, type FcmWebpushConfig, type LunoraNotify, type LunoraPush, type NotificationMessage, type NotifyConfig, type NotifyDefinition, type NotifyDeliveryStatus, type NotifyEnv, type NotifyLogger, type NotifyMetrics, type NotifySkipReason, type PushBroadcastJob, type PushBroadcastPageOutcome, type PushOwner, type PushSubscriptionDevice, type PushSubscriptionsResult, type QueueProducerLike, type RegisterInput, type ResolvedProviders, type RoutingPushOptions, type StoredSubscription, type SubscriptionFilter, type SubscriptionKind, type SubscriptionOutcomes, type SubscriptionStatus, type SubscriptionStore,
|
|
950
1089
|
/**
|
|
951
1090
|
* `@lunora/notify`
|
|
952
1091
|
*
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FCM_ENV_KEYS as e,WEB_PUSH_ENV_KEYS as t,fcmFromEnv as i,webPushFromEnv as s}from"./packem_shared/FCM_ENV_KEYS-DyR2MZ31.mjs";import{defineNotify as n,isNotifyDefinition as a}from"./packem_shared/defineNotify-DVPpVkU0.mjs";import{createNotify as u}from"./packem_shared/createNotify-
|
|
1
|
+
import{FCM_ENV_KEYS as e,WEB_PUSH_ENV_KEYS as t,fcmFromEnv as i,webPushFromEnv as s}from"./packem_shared/FCM_ENV_KEYS-DyR2MZ31.mjs";import{defineNotify as n,isNotifyDefinition as a}from"./packem_shared/defineNotify-DVPpVkU0.mjs";import{createNotify as u}from"./packem_shared/createNotify-DHMOcL17.mjs";import{b as E,r as d}from"./packem_shared/providers-CZaNFGWC.mjs";import{enqueuePushBroadcast as P,runPushBroadcastPage as c}from"./packem_shared/enqueuePushBroadcast-C4AJpS6v.mjs";import{d1SubscriptionStore as b}from"./packem_shared/d1SubscriptionStore-F2QkHI0n.mjs";import{memorySubscriptionStore as h}from"./packem_shared/memorySubscriptionStore-Pwb6nZpQ.mjs";import{f as _,i as y,n as v,t as w,w as B}from"./packem_shared/normalize--gkXcjKt.mjs";export{e as FCM_ENV_KEYS,t as WEB_PUSH_ENV_KEYS,E as buildEngine,u as createNotify,b as d1SubscriptionStore,n as defineNotify,P as enqueuePushBroadcast,i as fcmFromEnv,_ as fcmId,y as isGoneError,a as isNotifyDefinition,h as memorySubscriptionStore,v as normalizeRegisterInput,d as routingPushProvider,c as runPushBroadcastPage,w as targetOf,s as webPushFromEnv,B as webPushId};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./evict-oldest-BNXsKx4s.mjs";import{g as i,b as c,a as t,d as h,r as o}from"./providers-CZaNFGWC.mjs";import"./normalize--gkXcjKt.mjs";export{i as attachResilience,c as buildEngine,t as checkPushTtl,h as checkPushUrgency,o as routingPushProvider};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{b as Z,c as q,a as R,d as $,e as N,f as H}from"./providers-CZaNFGWC.mjs";import{memorySubscriptionStore as J}from"./memorySubscriptionStore-Pwb6nZpQ.mjs";import{n as K,t as V,i as X}from"./normalize--gkXcjKt.mjs";const Y=250,y=(n,u)=>typeof n=="function"?n(u):n,T=n=>n.successful?void 0:n.errorMessages.join("; "),ee=(n,u,d)=>n.successful?"accepted":X(u,d)?"gone":"failed",te=async(n,u,d)=>{const c=Array.from({length:n.length});let m=0;const k=async()=>{for(;m<n.length;){const g=m;m+=1,c[g]=await d(n[g])}};return await Promise.all(Array.from({length:Math.min(u,n.length)},()=>k())),c},D=(n,{fcm:u})=>{R(n.ttl),$(n.urgency),N(n,{fcm:u})},re=(n,u)=>({allowedPushOrigins:n.allowedPushOrigins,chat:y(n.chat,u),fcm:y(n.fcm,u),inApp:y(n.inApp,u),webhook:y(n.webhook,u),webPush:y(n.webPush,u)}),_=new WeakMap,oe=(n,u)=>{let d=_.get(n);d===void 0&&(d=new WeakMap,_.set(n,d));let c=d.get(u);return c===void 0&&(c={warnedNoPushOriginAllowlist:!1,warnedNoStore:!1},d.set(u,c)),c},ue=(n,u,d={})=>{const c=oe(n,u),m=()=>(c.resolved??=re(n,u),c.resolved),k=()=>{if(c.fcm===void 0){const e=d.engine===void 0?m().fcm:y(n.fcm,u);c.fcm=e===void 0?null:q(e)}return c.fcm};let g;d.engine===void 0?(c.engine??=Z(m(),k()??void 0),g=c.engine):g=d.engine,c.store??=n.store?.(u);let{store:P}=c;P===void 0&&(c.fallbackStore??=J(),!d.silent&&!c.warnedNoStore&&(c.warnedNoStore=!0,console.warn("@lunora/notify: no `store` configured — using a non-durable in-memory subscription store. Configure `store: (env) => d1SubscriptionStore(env.DB)` for production.")),P=c.fallbackStore);const h=P,L=Math.max(1,d.concurrency??n.concurrency??10),O=Math.max(1,d.broadcastPageSize??n.broadcastPageSize??Y),{log:z,metrics:C}=d,w=(e,t,o,s=1)=>{C?.count("notify.send",s,{channel:e,provider:t??e,status:o})},v=(e,t)=>{try{z?.warn(e,t)}catch{}},S=(e,t,o)=>{v(`notify ${e} delivery failed`,{channel:e,provider:t??e,status:"failed",...o})},b=(e,t)=>{C?.count("notify.skipped",1,{channel:e,reason:t})},j=()=>{const e=n.allowedPushOrigins!==void 0&&n.allowedPushOrigins.length>0;d.silent||e||c.warnedNoPushOriginAllowlist||(c.warnedNoPushOriginAllowlist=!0,console.warn("@lunora/notify: Web Push registered without `allowedPushOrigins` — endpoints are guarded by a string classifier at register time and a best-effort DNS re-check at send time, both of which are defeatable. Set `allowedPushOrigins` to the exact push-service origins for a hard guarantee."))},B=async e=>(await h.list(e)).map(({keys:o,token:s,...i})=>i),U=async e=>{if(typeof e!="string")return e;const t=await h.get(e);if(t===void 0)throw new p("BAD_REQUEST",`@lunora/notify: no registered subscription with id "${e}"`);return t},I=async(e,t,{countInline:o,deferStatus:s})=>{let i,l,r;try{i=await g.sendToChannel("push",{...t,to:V(e)}),l=T(i),r=ee(i,l,e.kind)}catch(a){r="failed",l=a instanceof Error?a.message:String(a)}if(!s)try{r==="accepted"?await h.markStatus(e.id,"ok"):r==="gone"?await h.delete(e.id):await h.markStatus(e.id,"failed",l)}catch(a){v("@lunora/notify: delivery status could not be recorded",{error:a instanceof Error?a.message:String(a),subscriptionId:e.id})}return r==="failed"&&S("push",e.kind,{error:l,subscriptionId:e.id,userId:e.userId??null}),o&&w("push",e.kind,r),{error:l,receipt:i,status:r}},W=async(e,t)=>{const o=await te(t,L,async r=>{const{error:a,status:f}=await I(r,e,{countInline:!1,deferStatus:!0});return{error:a,kind:r.kind,status:f,subscription:r}}),s={failed:[],gone:[],ok:[]};for(const{error:r,status:a,subscription:f}of o)a==="accepted"?s.ok.push(f.id):a==="gone"?s.gone.push(f.id):s.failed.push({error:r,id:f.id});try{h.applyOutcomes===void 0?await Promise.all([...s.ok.map(r=>h.markStatus(r,"ok")),...s.failed.map(({error:r,id:a})=>h.markStatus(a,"failed",r)),...s.gone.map(r=>h.delete(r))]):await h.applyOutcomes(s)}catch(r){v("@lunora/notify: page delivery statuses could not be recorded",{error:r instanceof Error?r.message:String(r),failed:s.failed.length,ok:s.ok.length})}const i=new Map;for(const{kind:r,status:a}of o){const f=`${r} ${a}`,A=i.get(f);A===void 0?i.set(f,{count:1,kind:r,status:a}):A.count+=1}for(const{count:r,kind:a,status:f}of i.values())w("push",a,f,r);const l=o.map(({error:r,status:a,subscription:f})=>a==="accepted"?{id:f.id,status:"ok"}:a==="gone"?{error:r,id:f.id,status:"expired"}:{error:r,id:f.id,status:"failed"});return{failed:l.filter(r=>r.status==="failed").length,outcomes:l,pruned:l.filter(r=>r.status==="expired").length,sent:l.filter(r=>r.status==="ok").length,total:l.length}},M=async(e,t)=>{if(D(e,{fcm:t?.kind!=="web-push"&&(d.engine!==void 0||k()!==null)}),t?.limit!==void 0&&t.limit<=0)return{nextCursor:void 0,result:{failed:0,outcomes:[],pruned:0,sent:0,total:0}};const o=t?.limit!==void 0&&t.limit>0?Math.trunc(t.limit):void 0,s=o===void 0?O:Math.min(o,O),i=await h.list({after:t?.after,kind:t?.kind,limit:s+1,userId:t?.userId}),l=t?.after===void 0?i:i.filter(Q=>Q.id>t.after),r=l.length>s,a=r?l.slice(0,s):l;a.length===0&&t?.after===void 0&&b("push","no-subscriptions-matched");const f=await W(e,a);return{nextCursor:r?a[a.length-1]?.id:void 0,result:f}},G=async(e,t)=>{const o={failed:0,outcomes:[],pruned:0,sent:0,total:0};let s=t?.after;const i=t?.limit;if(i!==void 0&&i<=0)return o;for(;;){const l=i===void 0?{...t,after:s}:{...t,after:s,limit:i-o.total},{nextCursor:r,result:a}=await M(e,l);if(o.failed+=a.failed,o.pruned+=a.pruned,o.sent+=a.sent,o.total+=a.total,o.outcomes.push(...a.outcomes),i!==void 0&&o.total>=i||r===void 0||r===s)break;s=r}return o},F=async(e,t)=>{D(t,{fcm:!0}),H(e);const o=k();if(o===null)throw b("push","channel-not-configured"),v("@lunora/notify: FCM topic or condition send with no fcm channel configured",{target:Object.keys(e).join(",")}),new p("INTERNAL","@lunora/notify: FCM topics and conditions need the `fcm` channel configured in defineNotify(...)");try{const s=await o.sendTo(e,t);return w("push","fcm","accepted"),{channel:"push",messageId:s,provider:"fcm",successful:!0,timestamp:new Date}}catch(s){if(s instanceof p)throw s;const i=s instanceof Error?s.message:String(s);throw w("push","fcm","failed"),S("push","fcm",{error:i}),new p("INTERNAL",`@lunora/notify: FCM send failed: ${i}`)}},x={broadcast:G,broadcastPage:M,list:e=>B(e),register:e=>("token"in e||j(),h.put(K(e,void 0,{allowedPushOrigins:n.allowedPushOrigins}))),send:async(e,t)=>{R(t.ttl),$(t.urgency),N(t,{fcm:!1});const o=await U(e);o.kind==="fcm"&&N(t,{fcm:!0});const{error:s,receipt:i}=await I(o,t,{countInline:!0,deferStatus:!1});if(i===void 0)throw new p("INTERNAL",`@lunora/notify: push send failed: ${s??"unknown error"}`);return i},sendToCondition:(e,t)=>F({condition:e},t),sendToTopic:(e,t)=>F({topic:e},t),unregister:async(e,t)=>{await h.deleteOwned(e,t.userId??null)}},E=async(e,t)=>{if(g.getProvider(e)===void 0)throw b(e,"channel-not-configured"),new p("BAD_REQUEST",`@lunora/notify: the "${e}" channel is not configured in defineNotify(...)`);const o=await g.sendToChannel(e,t),s=o.successful?"accepted":"failed";return w(e,o.provider,s),s==="failed"&&S(e,o.provider,{error:T(o)}),o};return{notify:{chat:e=>E("chat",e),inApp:e=>E("inapp",e),push:x,send:async e=>{const t=await g.send(e);for(const o of t){const s=o.channel??"unknown",i=o.successful?"accepted":"failed";w(s,o.provider,i),i==="failed"&&S(s,o.provider,{error:T(o)})}return t},webhook:e=>E("webhook",e)},push:x}};export{ue as createNotify};
|
package/dist/packem_shared/{d1SubscriptionStore-B13P2ERZ.mjs → d1SubscriptionStore-F2QkHI0n.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as O}from"@lunora/errors";import{c as $,l as L}from"./normalize
|
|
1
|
+
import{LunoraError as O}from"@lunora/errors";import{c as $,l as L}from"./normalize--gkXcjKt.mjs";const f=e=>/^[A-Z_]\w*$/i.test(e),R=e=>{const s={createdAt:e.created_at,id:e.id,kind:e.kind,lastSeenAt:e.last_seen_at,userId:e.user_id};if(e.endpoint!==null&&(s.endpoint=e.endpoint),e.p256dh!==null&&e.auth!==null&&(s.keys={auth:e.auth,p256dh:e.p256dh}),e.token!==null&&(s.token=e.token),e.last_status!==null&&(s.lastStatus=e.last_status),e.last_error!==null&&(s.lastError=e.last_error),e.metadata!==null)try{s.metadata=JSON.parse(e.metadata)}catch{}return s},h=90,F=(e,s={})=>{const n=s.tableName??"lunora_push_subscriptions";if(!f(n))throw new O("BAD_REQUEST",`@lunora/notify: d1SubscriptionStore tableName "${n}" is not a bare SQL identifier`);let p;const E=()=>(p===void 0&&(p=e.prepare(`CREATE TABLE IF NOT EXISTS ${n} (id TEXT PRIMARY KEY, kind TEXT NOT NULL, endpoint TEXT, p256dh TEXT, auth TEXT, token TEXT, user_id TEXT, metadata TEXT, created_at INTEGER NOT NULL, last_seen_at INTEGER NOT NULL, last_status TEXT, last_error TEXT)`).run().then(()=>e.prepare(`CREATE INDEX IF NOT EXISTS ${n}_user_id_idx ON ${n} (user_id)`).run()).then(()=>e.prepare(`CREATE INDEX IF NOT EXISTS ${n}_kind_idx ON ${n} (kind)`).run()).then(()=>{}),p.catch(()=>{p=void 0})),p),S=async t=>{await E();const a=await e.prepare(`SELECT * FROM ${n} WHERE id = ?1`).bind(t).first();return a===null?void 0:R(a)};return{applyOutcomes:async({failed:t,gone:a,ok:r})=>{await E();const u=Date.now(),d=[],c=(i,l,o)=>{for(let T=0;T<o.length;T+=h){const N=o.slice(T,T+h),m=N.map((v,I)=>`?${(I+4).toString()}`).join(", ");d.push(e.prepare(`UPDATE ${n} SET last_status = ?1, last_error = ?2, last_seen_at = ?3 WHERE id IN (${m})`).bind(i,l,u,...N))}};c("ok",null,r);const _=new Map;for(const{error:i,id:l}of t){const o=_.get(i??null);o===void 0?_.set(i??null,[l]):o.push(l)}for(const[i,l]of _)c("failed",i,l);for(let i=0;i<a.length;i+=h){const l=a.slice(i,i+h);d.push(e.prepare(`DELETE FROM ${n} WHERE id IN (${l.map((o,T)=>`?${(T+1).toString()}`).join(", ")})`).bind(...l))}d.length>0&&await e.batch(d)},delete:async t=>{await E(),await e.prepare(`DELETE FROM ${n} WHERE id = ?1`).bind(t).run()},deleteOwned:async(t,a)=>(await E(),await(a===null?e.prepare(`DELETE FROM ${n} WHERE id = ?1 AND user_id IS NULL RETURNING id`).bind(t):e.prepare(`DELETE FROM ${n} WHERE id = ?1 AND user_id = ?2 RETURNING id`).bind(t,a)).first()!==null),get:S,list:async t=>{await E();const a=[],r=[];t?.kind!==void 0&&(r.push(t.kind),a.push(`kind = ?${r.length.toString()}`)),t?.userId!==void 0&&(t.userId===null?a.push("user_id IS NULL"):(r.push(t.userId),a.push(`user_id = ?${r.length.toString()}`))),t?.after!==void 0&&(r.push(t.after),a.push(`id > ?${r.length.toString()}`));const u=a.length===0?"":` WHERE ${a.join(" AND ")}`,d=" ORDER BY id ASC";let c="";t?.limit!==void 0&&t.limit>0&&(r.push(Math.trunc(t.limit)),c=` LIMIT ?${r.length.toString()}`);const{results:_}=await e.prepare(`SELECT * FROM ${n}${u}${d}${c}`).bind(...r).all();return _.map(i=>R(i))},markStatus:async(t,a,r)=>{await E(),await e.prepare(`UPDATE ${n} SET last_status = ?2, last_error = ?3, last_seen_at = ?4 WHERE id = ?1`).bind(t,a,r??null,Date.now()).run()},put:async t=>{await E(),await e.prepare(`INSERT INTO ${n} (id, kind, endpoint, p256dh, auth, token, user_id, metadata, created_at, last_seen_at, last_status, last_error) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12) ON CONFLICT(id) DO UPDATE SET kind = ?2, endpoint = ?3, p256dh = ?4, auth = ?5, token = ?6, user_id = ?7, metadata = ?8, last_seen_at = ?10 WHERE ${n}.user_id IS NULL OR ${n}.user_id = ?7`).bind(t.id,t.kind,t.endpoint??null,t.keys?.p256dh??null,t.keys?.auth??null,t.token??null,t.userId??null,t.metadata===void 0?null:JSON.stringify(t.metadata),t.createdAt,t.lastSeenAt,t.lastStatus??null,t.lastError??null).run();const a=await S(t.id),r=$(a,t);if(r!==void 0)throw r;const u=L(t);if(u!==void 0&&u!==t.id){const d=t.userId??null;await(d===null?e.prepare(`DELETE FROM ${n} WHERE id = ?1 AND user_id IS NULL`).bind(u):e.prepare(`DELETE FROM ${n} WHERE id = ?1 AND (user_id IS NULL OR user_id = ?2)`).bind(u,d)).run()}return a??t}}};export{F as d1SubscriptionStore};
|
package/dist/packem_shared/{enqueuePushBroadcast-C9tO0BZj.mjs → enqueuePushBroadcast-C4AJpS6v.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as d}from"@lunora/errors";import{i as c,k as f}from"./normalize
|
|
1
|
+
import{LunoraError as d}from"@lunora/errors";import{i as c,k as f}from"./normalize--gkXcjKt.mjs";const u=r=>r.filter(t=>t.status==="failed").map(t=>t.id),v=(r,t)=>r.send({...t,type:"lunora.push.broadcast"}),g=(r,t,s)=>{if(t===void 0)return;if(r?.limit===void 0)return{...r,after:t};const e=r.limit-s;return e>0?{...r,after:t,limit:e}:void 0},h=/no registered subscription/u,p=async(r,t,s)=>{try{const e=await r.send(s,t);if(e.successful)return{id:s,status:"ok"};const n=e.errorMessages.join("; ");return{error:n,id:s,status:c(n,f(s))?"expired":"failed"}}catch(e){const n=e instanceof Error?e.message:String(e);return{error:n,id:s,status:h.test(n)?"expired":"failed"}}},y=async(r,t,s)=>{const e=[];for(const o of s)e.push(await p(r,t,o));const n=u(e),a=e.filter(o=>o.status==="expired").length,i=e.length-n.length-a,l={failed:n.length,outcomes:e,pruned:a,sent:i,total:e.length};if(i===0&&n.length>0)throw new d("INTERNAL",`@lunora/notify: push retry failed for ${n.length.toString()} of ${e.length.toString()} subscription(s) — throwing so the queue retries and eventually dead-letters them`);return{failedIds:n,nextFilter:void 0,result:l}},w=async(r,t)=>{if(t.retryIds!==void 0&&t.retryIds.length>0)return y(r,t.payload,t.retryIds);const s=await r.broadcastPage(t.payload,t.filter);return{failedIds:u(s.result.outcomes),nextFilter:g(t.filter,s.nextCursor,s.result.total),result:s.result}};export{v as enqueuePushBroadcast,w as runPushBroadcastPage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as e,f as r,i as c,k as d,e as l,l as I,g as f,n as g,t as i,w as o}from"./normalize
|
|
1
|
+
import{c as e,f as r,i as c,k as d,e as l,l as I,g as f,n as g,t as i,w as o}from"./normalize--gkXcjKt.mjs";export{e as claimRefusal,r as fcmId,c as isGoneError,d as kindOfId,l as legacyFcmId,I as legacyIdFor,f as legacyWebPushId,g as normalizeRegisterInput,i as targetOf,o as webPushId};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as a,l}from"./normalize
|
|
1
|
+
import{c as a,l}from"./normalize--gkXcjKt.mjs";const u=(t,e)=>t.id<e.id?-1:t.id>e.id?1:0,c=(t,e)=>e===void 0?!0:!(e.kind!==void 0&&t.kind!==e.kind||e.userId!==void 0&&(t.userId??null)!==e.userId),m=()=>{const t=new Map;return{delete:e=>(t.delete(e),Promise.resolve()),deleteOwned:(e,r)=>{const s=t.get(e);return s===void 0||(s.userId??null)!==r?Promise.resolve(!1):(t.delete(e),Promise.resolve(!0))},get:e=>Promise.resolve(t.get(e)),list:e=>{const r=[];for(const o of t.values())c(o,e)&&r.push(o);r.sort(u);const s=e?.after===void 0?r:r.filter(o=>o.id>e.after),d=e?.limit!==void 0&&e.limit>0?s.slice(0,Math.trunc(e.limit)):s;return Promise.resolve(d)},applyOutcomes:({failed:e,gone:r,ok:s})=>{const d=Date.now();for(const o of s){const i=t.get(o);i!==void 0&&t.set(o,{...i,lastError:void 0,lastSeenAt:d,lastStatus:"ok"})}for(const{error:o,id:i}of e){const n=t.get(i);n!==void 0&&t.set(i,{...n,lastError:o,lastSeenAt:d,lastStatus:"failed"})}for(const o of r)t.delete(o);return Promise.resolve()},markStatus:(e,r,s)=>{const d=t.get(e);return d!==void 0&&t.set(e,{...d,lastError:s,lastSeenAt:Date.now(),lastStatus:r}),Promise.resolve()},put:e=>{const r=t.get(e.id),s=a(r,e);if(s!==void 0)return Promise.reject(s);const d=r===void 0?e:{...r,...e,createdAt:r.createdAt};t.set(d.id,d);const o=l(e),i=o===void 0||o===e.id?void 0:t.get(o);return i!==void 0&&a(i,e)===void 0&&t.delete(i.id),Promise.resolve(d)}}};export{m as memorySubscriptionStore};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as f}from"@lunora/errors";const b=/^\d{1,3}$/u,S=/^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u,P=/^::ffff:0:([\da-f]{1,4}):([\da-f]{1,4})$/u,N=/^::[\da-f]{1,4}$/u,O=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/u,D=/^::(\d{1,3}(?:\.\d{1,3}){3})$/u
|
|
1
|
+
import{LunoraError as f}from"@lunora/errors";const b=/^\d{1,3}$/u,S=/^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u,P=/^::ffff:0:([\da-f]{1,4}):([\da-f]{1,4})$/u,N=/^::[\da-f]{1,4}$/u,O=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/u,D=/^::(\d{1,3}(?:\.\d{1,3}){3})$/u,R=/^::([\da-f]{1,4}):([\da-f]{1,4})$/u,$=/^64:ff9b::[\da-f]{1,4}:[\da-f]{1,4}$/u,W=/^[\da-f]{1,4}$/u,B=[[[8193],23],[[16383],20],[[24320],16],[[256,0,0,1],64]],k=[[[8193,1,0,0,0,0,0,1],128],[[8193,1,0,0,0,0,0,2],128],[[8193,1,0,0,0,0,0,3],128],[[8193,3],32],[[8193,4,274],48],[[8193,5],32],[[8193,32],28],[[8193,48],28]],x=t=>{const e=t.split("::");if(e.length>2)return;const n=a=>a===void 0||a===""?[]:a.split(":").map(o=>W.test(o)?Number.parseInt(o,16):Number.NaN),r=n(e[0]),i=n(e[1]),s=8-r.length-i.length;if(s<0||e.length===1&&s!==0)return;const c=[...r,...Array.from({length:s},()=>0),...i];return c.some(Number.isNaN)?void 0:c},_=(t,[e,n])=>{for(let r=0;r*16<n;r+=1){const s=65535<<16-Math.min(16,n-r*16)&65535;if(((t[r]??0)&s)!==((e[r]??0)&s))return!1}return!0},L=/^\[|\]$/gu,M=/\.$/u,p=t=>{const e=t.split(".");if(e.length!==4)return;const n=e.map(r=>b.test(r)?Number(r):-1);if(!n.some(r=>r<0||r>255))return[n[0],n[1],n[2],n[3]]},l=([t,e,n])=>t===0||t===10||t===127||t===100&&e>=64&&e<=127||t===169&&e===254||t===172&&e>=16&&e<=31||t===192&&e===0&&(n===0||n===2)||t===192&&e===88&&n===99||t===192&&e===168||t===198&&(e===18||e===19)||t===198&&e===51&&n===100||t===203&&e===0&&n===113||t>=224,h=(t,e)=>{const n=Number.parseInt(t??"",16),r=Number.parseInt(e??"",16);return!Number.isFinite(n)||!Number.isFinite(r)?!0:l([Math.floor(n/256),n%256,Math.floor(r/256),r%256])},F=t=>{const e=t.toLowerCase(),n=S.exec(e);if(n)return h(n[1],n[2]);const r=P.exec(e);if(r)return h(r[1],r[2]);const i=O.exec(e);if(i){const o=p(i[1]??"");return o===void 0||l(o)}const s=D.exec(e);if(s){const o=p(s[1]??"");return o===void 0||l(o)}const c=R.exec(e);if(c)return h(c[1],c[2]);if(N.test(e)||$.test(e)||e.startsWith("64:ff9b:1:")||e.startsWith("2002:"))return!0;const a=x(e);return a!==void 0&&B.some(o=>_(a,o))&&!k.some(o=>_(a,o))?!0:e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||e.startsWith("fe8")||e.startsWith("fe9")||e.startsWith("fea")||e.startsWith("feb")||e.startsWith("fec")||e.startsWith("fed")||e.startsWith("fee")||e.startsWith("fef")||e.startsWith("ff")||e.startsWith("2001:db8:")||e.startsWith("100::")},U=t=>t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa"),V=t=>t.replaceAll(L,"").replace(M,"").toLowerCase(),C=t=>{const e=V(t);if(e.includes(":"))return F(e);const n=p(e);return n===void 0?U(e):l(n)},H=2166136261,G=16777619,Q=(t,e=H)=>{let n=e;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,G);return(n>>>0).toString(16).padStart(8,"0")},u=t=>t.toString(16).padStart(4,"0"),A=t=>{let e=8997,n=33826,r=40164,i=52210;for(let s=0;s<t.length;s+=1){e^=t.charCodeAt(s);const c=e*435,a=n*435,o=r*435+e*256,I=i*435+n*256,E=a+(c>>>16),g=o+(E>>>16),T=I+(g>>>16);e=c&65535,n=E&65535,r=g&65535,i=T&65535}return u(i)+u(r)+u(n)+u(e)},m=4096,X=2048,j=2048,y=512,d=(t,e,n)=>{const r=new TextEncoder().encode(t).length;if(r>e)throw new f("BAD_REQUEST",`@lunora/notify: register() \`${n}\` is ${r.toString()} bytes, exceeding the ${e.toString()}-byte cap`)},v=t=>{if(t===void 0)return;const e=typeof t=="object"&&t!==null?Object.getPrototypeOf(t):void 0;if(!(typeof t=="object"&&t!==null&&!Array.isArray(t)&&(e===Object.prototype||e===null)))throw new f("BAD_REQUEST","@lunora/notify: register() `metadata` must be a plain object");let r;try{r=JSON.stringify(t)}catch(s){throw new f("BAD_REQUEST",`@lunora/notify: register() \`metadata\` is not JSON-serialisable: ${s instanceof Error?s.message:String(s)}`)}const i=new TextEncoder().encode(r).length;if(i>m)throw new f("BAD_REQUEST",`@lunora/notify: register() \`metadata\` is ${i.toString()} bytes, exceeding the ${m.toString()}-byte cap`);return t},Y=t=>`wp2_${A(t)}`,z=t=>`fcm2_${A(t)}`,ot=t=>t.startsWith("fcm2_")||t.startsWith("fcm_")?"fcm":t.startsWith("wp2_")||t.startsWith("wp_")?"web-push":void 0,w=t=>Q(t),J=t=>`wp_${w(t)}`,K=t=>`fcm_${w(t)}`,it=t=>t.kind==="fcm"?t.token===void 0?void 0:K(t.token):t.endpoint===void 0?void 0:J(t.endpoint),ct=(t,e)=>{const n=t?.userId??null;if(!(t===void 0||n===null||n===(e.userId??null)))return new f("FORBIDDEN",`@lunora/notify: subscription "${e.id}" is registered to a different user; a device must be unregistered by its owner before another account can claim it`)},q=t=>{if(typeof t!="string")return t??{};try{return JSON.parse(t)}catch(e){throw new f("BAD_REQUEST",`@lunora/notify: register() web-push subscription is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}},Z=(t,e)=>{let n;try{n=new URL(t)}catch{throw new f("BAD_REQUEST",`@lunora/notify: register() web-push \`endpoint\` must be an absolute https URL (got "${t}")`)}if(n.protocol!=="https:")throw new f("BAD_REQUEST",`@lunora/notify: register() web-push \`endpoint\` must use https (got "${n.protocol}")`);if(e!==void 0&&e.length>0){if(!e.includes(n.origin))throw new f("FORBIDDEN",`@lunora/notify: register() web-push endpoint origin "${n.origin}" is not in the configured allowedPushOrigins allowlist`);return}if(C(n.hostname))throw new f("FORBIDDEN",`@lunora/notify: register() web-push endpoint host "${n.hostname}" is a private/internal address; configure allowedPushOrigins to permit a specific origin`)},at=(t,e=Date.now(),n={})=>{if(t.kind===void 0?t.token!==void 0:t.kind==="fcm"){const{token:o}=t;if(typeof o!="string"||o==="")throw new f("BAD_REQUEST","@lunora/notify: register() fcm input requires a non-empty `token`");return d(o,j,"token"),{createdAt:e,id:z(o),kind:"fcm",lastSeenAt:e,metadata:v(t.metadata),token:o,userId:t.userId??null}}const i=q(t.subscription),{endpoint:s}=i,c=i.keys?.p256dh,a=i.keys?.auth;if(typeof s!="string"||s===""||typeof c!="string"||typeof a!="string")throw new f("BAD_REQUEST","@lunora/notify: register() web-push subscription requires `endpoint` and `keys.{p256dh, auth}`");return d(s,X,"endpoint"),d(a,y,"keys.auth"),d(c,y,"keys.p256dh"),Z(s,n.allowedPushOrigins),{createdAt:e,endpoint:s,id:Y(s),keys:{auth:a,p256dh:c},kind:"web-push",lastSeenAt:e,metadata:v(t.metadata),userId:t.userId??null}},ft=t=>t.kind==="fcm"?t.token??"":JSON.stringify({endpoint:t.endpoint,keys:t.keys}),tt=/\bhttp\s*4(?:04|10)\b/iu,et=/^(?:\[[^\]]*\]\s*)*FCM 404 UNREGISTERED: /u,nt=/\b(?:unregistered|not[\s-]?registered|registration-token-not-registered)\b/iu,rt=/\bsubscription (?:is )?(?:gone|expired|no longer valid)\b/iu,ut=(t,e)=>t===void 0?!1:e==="fcm"?et.test(t):tt.test(t)||rt.test(t)?!0:e!=="web-push"&&nt.test(t);export{V as a,l as b,ct as c,F as d,K as e,z as f,J as g,ut as i,ot as k,it as l,at as n,p,ft as t,Y as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as m,isLunoraError as W}from"@lunora/errors";import{createNotification as K}from"@visulima/notification";import{retryMiddleware as H}from"@visulima/notification/middleware";import{createWebPushProvider as Z}from"@visulima/notification/providers/web-push";import{e as ee}from"./evict-oldest-BNXsKx4s.mjs";import{a as te,p as Y,b as re,d as se,i as z}from"./normalize--gkXcjKt.mjs";const ne=e=>{let t=e.length;for(;t>0&&e.charAt(t-1)==="/";)t-=1;return e.slice(0,t)},V="https://fcm.googleapis.com",oe=4,ie=1,ce=10,ae=3e4,N=64*1024,de=3e4,P=/^[\w.~%-]+$/u,ue=e=>{if(typeof e!="object"||e===null||!("errorCode"in e))return;const t=e.errorCode;return typeof t=="string"?t:void 0},fe=/^[A-Z_]+$/u,le=e=>{if(Array.isArray(e))for(const t of e){const r=ue(t);if(r!==void 0&&fe.test(r))return r}},he=e=>Array.isArray(e)&&e.some(t=>typeof t=="object"&&t!==null&&"errorCode"in t&&t.errorCode==="UNREGISTERED"),pe=(e,t)=>{const r=t?.error,n=typeof r?.message=="string"?r.message:"request failed",s=typeof r?.status=="string"?r.status:void 0,o=s!==void 0&&s!=="UNREGISTERED"?s:"ERROR",c=le(r?.details),i=he(r?.details)?"UNREGISTERED":c??o;return`FCM ${String(e)} ${i}: ${n}`},me=async e=>{const t=e.body?.getReader();if(t===void 0)return"";const r=[];let n=0,s=await t.read();for(;!s.done;){if(n+=s.value.byteLength,n>N)throw await t.cancel(),new Error(`FCM response is larger than ${String(N)} bytes`);r.push(s.value),s=await t.read()}const o=new Uint8Array(n);let c=0;for(const i of r)o.set(i,c),c+=i.byteLength;return new TextDecoder().decode(o)},I=e=>{try{return JSON.parse(e)}catch{return}},A=e=>e instanceof Error?e.message:String(e),S=e=>e!==void 0&&e!=="",ve=e=>e===void 0?void 0:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,typeof r=="string"?r:JSON.stringify(r)])),ge=e=>e==="high"?"HIGH":"NORMAL",we=e=>e==="high"?"10":e==="low"||e==="very-low"?"5":void 0,F=(e,t)=>{if(t===void 0)return e;const r=new Set(Object.keys(t).map(s=>s.toLowerCase())),n=Object.entries(e).filter(([s])=>!r.has(s.toLowerCase()));return{...Object.fromEntries(n),...t}},w=e=>Object.values(e).some(t=>t!==void 0)?e:void 0,$=(e,t)=>{const r=e.fcmOverrides,n=S(e.title)||S(e.body)||S(e.imageUrl),s=e.ttl===void 0?void 0:String(e.ttl),o=e.ttl===void 0?void 0:String(Math.floor(Date.now()/1e3)+e.ttl),c=e.urgency===void 0?void 0:ge(e.urgency),i=e.urgency===void 0?void 0:we(e.urgency),d=w({click_action:e.clickAction,sound:e.sound,...r?.android?.notification}),v=w({ttl:e.ttl===void 0?void 0:`${String(e.ttl)}s`,priority:c,...r?.android,notification:d}),l=w({badge:e.badge,sound:e.sound,...r?.apns?.payload?.aps}),h=w({...r?.apns,headers:w(F({"apns-expiration":o,"apns-priority":i},r?.apns?.headers)),payload:w({...r?.apns?.payload,aps:l})}),a=w({...r?.webpush,headers:w(F({TTL:s,Urgency:e.urgency},r?.webpush?.headers))});return{...t,android:v,apns:h,data:ve(e.data),fcm_options:r?.fcm_options,notification:n?{body:e.body,image:e.imageUrl,title:e.title}:void 0,webpush:a}},Ee=e=>e===408||e===429||e>=500,U=1e4,ye=e=>{if(e===null||e.trim()==="")return;const t=Number(e);if(Number.isFinite(t))return Math.max(0,t*1e3);const r=Date.parse(e);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())},be=e=>e!==void 0&&Number.isFinite(e)&&e>0?e:de,Te=(e,t)=>e!==void 0&&Number.isFinite(e)?Math.min(ce,Math.max(1,Math.trunc(e))):t,J=e=>e instanceof Error?e:new Error(String(e)),Ae=/^(?:\[[^\]]*\]\s*)*FCM (?:200|400|401|403|404|413) /u,Se=/\bRetry-After exceeds the \d+s wait limit\b/u,Q=e=>Ae.test(e)||Se.test(e),Re=(e,t)=>t?e===429:Ee(e),L=(e,t,r,n)=>Re(t,r)?n!==void 0&&n>U?{error:new Error(`${e.message} (Retry-After exceeds the ${String(U/1e3)}s wait limit)`),kind:"final"}:{error:e,kind:"retry",retryAfterMs:n}:{error:e,kind:"final"},_e=async(e,t)=>{const r=ye(e.headers.get("retry-after"));let n;try{n=await me(e)}catch(s){const o=J(s);return e.ok?{error:new Error(`FCM ${String(e.status)} ACCEPTED_UNREADABLE: ${o.message}`),kind:"final"}:L(new Error(`FCM ${String(e.status)} ERROR: ${o.message}`),e.status,t,r)}if(e.ok){const s=I(n)?.name;return typeof s=="string"&&s!==""?{kind:"done",messageName:s}:{error:new Error("FCM 200 ACCEPTED_NO_NAME: the request was accepted but returned no message name"),kind:"final"}}return L(new Error(pe(e.status,I(n))),e.status,t,r)},Ce=async(e,t,r,n,s,o)=>{try{const c=await s(e,{body:t,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(n)});return await _e(c,o)}catch(c){return{error:J(c),kind:o?"final":"retry"}}},j=async(e,t,r,n,s,o)=>{const i=`${ne(e.endpoint??V)}/v1/projects/${e.projectId}/messages:send`,d=JSON.stringify({message:r}),v=s.retryBaseDelay??250,l=be(e.timeout);let h=new Error("FCM send failed"),a;for(let f=0;f<n;f+=1){if(f>0){const p=Math.floor(Math.random()*v),E=Math.min(v*2**(f-1)+p,ae);await new Promise(u=>{setTimeout(u,Math.max(E,a??0))})}const g=await Ce(i,d,t,l,s.fetch??fetch,o);if(g.kind==="done")return g.messageName;if(h=g.error,g.kind==="final")throw h;a=g.retryAfterMs}throw!o&&a!==void 0&&a>0&&await new Promise(f=>{setTimeout(f,a)}),h},De=e=>{if("topic"in e&&!P.test(e.topic))throw new m("BAD_REQUEST",`@lunora/notify: FCM topic ${JSON.stringify(e.topic)} must match ${String(P)}`);if("condition"in e&&e.condition.trim()==="")throw new m("BAD_REQUEST","@lunora/notify: FCM condition must be a non-empty expression")},Me=(e,t={})=>{const r=()=>{if(!e.projectId)throw new Error("FCM projectId is not configured")},n=async()=>{if(e.getAccessToken!==void 0)return e.getAccessToken();if(e.accessToken!==void 0&&e.accessToken!=="")return e.accessToken;throw new Error("FCM has no access token: set FCM_SERVICE_ACCOUNT, or pass getAccessToken to the fcm channel")},s=Te(t.maxAttempts??(e.retries===void 0?void 0:e.retries+1),oe),o=async(i,d)=>(De(i),r(),j(e,await n(),$(d,i),s,t,!0));return{provider:{channel:"push",endpoint:e.endpoint??V,features:{batchSending:!1,media:!0,richContent:!0},id:"fcm",initialize:()=>{},isAvailable:()=>!!(e.projectId&&(e.getAccessToken!==void 0||e.accessToken!==void 0&&e.accessToken!=="")),options:e,send:async i=>{if(i.ttl!==void 0&&(!Number.isInteger(i.ttl)||i.ttl<0))return{error:new Error(`push ttl must be a non-negative integer, got ${String(i.ttl)}`),success:!1};try{r()}catch(a){return{error:new Error(A(a)),success:!1}}let d;try{d=await n()}catch(a){return{error:new Error(`FCM access token unavailable: ${A(a)}`),success:!1}}const v=Array.isArray(i.to)?i.to:[i.to],l=[];for(const a of v)try{const f=await j(e,d,$(i,{token:a}),ie,t,!1);l.push({id:a,messageId:f,status:"sent"})}catch(f){l.push({error:A(f),id:a,status:"failed"})}const h=l.find(a=>a.status==="sent");if(h===void 0){const a=l.filter(p=>p.status==="failed"),g=a.find(p=>!Q(p.error??""))??a[0];return{error:new Error(g?.error??"All recipients failed"),success:!1}}return{data:{channel:"push",messageId:h.messageId??"",provider:"fcm",recipients:l,sent:!0,timestamp:new Date},success:!0}}},sendTo:o}},B=4096,ke=e=>typeof e=="string"?e:JSON.stringify(e),Oe=(e,{fcm:t=!1}={})=>{const r=e.data===void 0?void 0:Object.fromEntries(Object.entries(e.data).map(([o,c])=>[o,ke(c)])),n=t?{badge:e.badge,clickAction:e.clickAction,fcmOverrides:e.fcmOverrides,sound:e.sound}:{},s=new TextEncoder().encode(JSON.stringify({body:e.body,data:r,image:e.imageUrl,title:e.title,...n})).length;if(s>B)throw new m("PAYLOAD_TOO_LARGE",`@lunora/notify: push payload is ${String(s)} bytes; FCM and Web Push accept at most ${String(B)} bytes`)},Ne="https://cloudflare-dns.com/dns-query",D=1,x=28,Pe=2e3,Ie=(e,t)=>{if(t===D){const r=Y(e);return r===void 0||re(r)}return se(e.toLowerCase())},G=async(e,t,r)=>{try{const n=await fetch(`${Ne}?name=${encodeURIComponent(e)}&type=${String(t)}`,{headers:{accept:"application/dns-json"},signal:AbortSignal.timeout(r)});if(!n.ok)return;const s=await n.json();return s.Status===void 0||s.Status===0?s.Answer??[]:[]}catch{return}},Fe=async(e,t=Pe)=>{const r=te(e);if(r.includes(":")||Y(r)!==void 0)return{kind:"skipped"};const[n,s]=await Promise.all([G(r,D,t),G(r,x,t)]);if(n===void 0||s===void 0)return{kind:"failed"};const o=[...n,...s].filter(c=>c.type===D||c.type===x);for(const c of o)if(Ie(c.data,c.type))return{address:c.data,kind:"private"};return o.length===0?{kind:"unresolved"}:{kind:"public"}},M=e=>{let t=e;if(typeof e=="string"){if(!e.startsWith("{"))return;try{t=JSON.parse(e)}catch{return}}const r=t?.endpoint;return typeof r=="string"?r:void 0},$e=e=>M(e)===void 0?"fcm":"web-push",b="lunora-push-router",R=new Map,Ue=256,Le=async(e,t)=>{if(t!==void 0&&t.length>0)return;let r;try{({hostname:r}=new URL(e))}catch{return}const n=R.get(r),s=n??Fe(r),o=await s;if(n===void 0&&(o.kind==="private"||o.kind==="public")&&(ee(R,Ue),R.set(r,s)),o.kind==="private")throw new m("FORBIDDEN",`@lunora/notify: web-push endpoint host "${r}" resolves to a private/internal address (${o.address}); refusing to send (DNS-rebinding guard)`);if(o.kind==="unresolved")throw new m("FORBIDDEN",`@lunora/notify: web-push endpoint host "${r}" did not resolve to any address; refusing to send (DNS-rebinding guard)`);if(o.kind==="failed")throw new m("FORBIDDEN",`@lunora/notify: could not verify where web-push endpoint host "${r}" resolves (the DNS-over-HTTPS lookup failed); refusing to send (DNS-rebinding guard)`)},je=(e,t)=>{const r=[e.provider,t.provider].filter(s=>s!==void 0),n=[...e.recipients??[],...t.recipients??[]];return{...e,messageId:[e.messageId,t.messageId].join(","),response:[e.response,t.response],sent:e.sent&&t.sent,timestamp:new Date(Math.max(e.timestamp.getTime(),t.timestamp.getTime())),...r.length>0?{provider:r.join(",")}:{},...n.length>0?{recipients:n}:{}}},O=e=>e instanceof Error?e.message:typeof e=="string"?e:void 0,q="PUSH_PARTIALLY_DELIVERED",X=e=>W(e)&&e.code===q,Be=e=>{if(!X(e))return;const{data:t}=e;return t==="fcm"||t==="web-push"?t:void 0},_=(e,t)=>{if(!e.success||!t.success){if(e.success||t.success){const[n,s]=e.success?["web-push","fcm"]:["fcm","web-push"],o=e.success?t.error:e.error;return{error:new m(q,`@lunora/notify: push partially delivered — the ${n} group was accepted, the ${s} group failed and re-attempting it did not recover it (${O(o)??"unknown error"}). The whole send is not retried: that would re-send to the ${n} targets that already received it. Re-send to the ${s} targets only.`,{cause:o,data:s}),success:!1}}return{error:new AggregateError([e.error,t.error],"@lunora/notify: both push target groups failed"),success:!1}}const r=e.data===void 0||t.data===void 0?e.data??t.data:je(e.data,t.data);return r===void 0?{success:!0}:{data:r,success:!0}},k=e=>{const t=O(e);return z(t)||t!==void 0&&Q(t)},xe=/^(?:\[[^\]]*\]\s*)*FCM (?:400 |413 |403 SENDER_ID_MISMATCH\b)/u,Ge=e=>{const t=O(e);return z(t)||t!==void 0&&xe.test(t)},y=5,He=3e4,Ye=e=>{if(e.provider!==b)return[e.provider];const{to:t}=e.payload,r=Array.isArray(t)?t:[t],n=new Set(r.map(s=>$e(s)));return n.size===0?[e.provider]:[...n].map(s=>`${e.provider}:${s}`)},ze=(e,t)=>e.failures>=y&&t-e.openedAt<He,Ve=(e,t,r)=>{const n=Be(e),s=n===void 0?void 0:`${b}:${n}`,o=s!==void 0&&t.includes(s);for(const[c,i]of r.entries())o&&t[c]!==s?i.failures=0:(i.failures+=1,i.failures>=y&&(i.openedAt=Date.now()))},Je=()=>{const e=new Map,t=r=>{const n=e.get(r);if(n!==void 0)return n;const s={failures:0,openedAt:0};return e.set(r,s),s};return async(r,n)=>{const s=Ye(r),o=s.map(d=>t(d)),c=Date.now();if(o.every(d=>ze(d,c)))return{error:new m("SERVICE_UNAVAILABLE",`@lunora/notify: circuit open for "${s.join('", "')}" after ${y.toString()} consecutive failures`),success:!1};for(const d of o)d.failures>=y&&(d.failures=y-1);const i=await n(r);if(i.success)for(const d of o)d.failures=0;else Ge(i.error)||Ve(i.error,s,o);return i}},Qe=2,C=async(e,t)=>{try{return await e.send(t)}catch(r){return{error:r,success:!1}}},qe=new Set(["high","low","normal","very-low"]),Xe=e=>qe.has(e),ot=e=>{if(e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0))throw new m("BAD_REQUEST",`@lunora/notify: push ttl must be a non-negative integer number of seconds, got ${typeof e=="number"?String(e):typeof e}`);return e},it=e=>{if(e!==void 0&&!Xe(e))throw new m("BAD_REQUEST",`@lunora/notify: push urgency must be "very-low", "low", "normal" or "high", got ${JSON.stringify(e)}`)},We=e=>{const t=H({baseDelay:e.retryBaseDelay,retries:Qe,shouldRetry:s=>!k(s)}),r=async(s,o,c)=>k(c.error)?c:t({channel:"push",payload:o,provider:b},async i=>C(s,i.payload)),n=s=>{const o=s===void 0?e.fcm:e.webPush;if(o===void 0)throw new Error(s===void 0?"@lunora/notify: received an FCM token target but no `fcm` channel is configured":"@lunora/notify: received a web-push target but no `webPush` channel is configured");return o};return{channel:"push",id:b,initialize:async()=>{await e.webPush?.initialize(),await e.fcm?.initialize()},isAvailable:()=>(e.webPush??e.fcm)!==void 0,send:async s=>{const o=Array.isArray(s.to)?s.to:[s.to];if(o.length===0)throw new m("BAD_REQUEST","@lunora/notify: push send has no recipients — `to` is an empty array");Oe(s,{fcm:o.some(u=>M(u)===void 0)});const c=o.map(u=>M(u));for(const u of c)u!==void 0&&await Le(u,e.allowedPushOrigins);const i=o.filter((u,T)=>c[T]!==void 0),d=o.filter((u,T)=>c[T]===void 0),v=c.find(u=>u!==void 0);if(d.length===0&&v!==void 0)return n(v).send(s);if(i.length===0)return n(void 0).send(s);const l=u=>({...s,to:u.length===1&&u[0]!==void 0?u[0]:u}),h=n(v),a=n(void 0),f=l(i),g=l(d),[p,E]=await Promise.all([C(h,f),C(a,g)]);return p.success&&!E.success?_(p,await r(a,g,E)):E.success&&!p.success?_(await r(h,f,p),E):_(p,E)}}},Ke=(e,t={})=>e.use(H({baseDelay:t.retryBaseDelay,shouldRetry:r=>!k(r)&&!X(r)})).use(Je()),ct=(e,t)=>{const r=e.webPush===void 0?void 0:Z(e.webPush),n=t?.provider??(e.fcm===void 0?void 0:Me(e.fcm).provider),s={};return(r!==void 0||n!==void 0)&&(s.push=We({allowedPushOrigins:e.allowedPushOrigins,fcm:n,webPush:r})),e.chat!==void 0&&(s.chat=e.chat),e.inApp!==void 0&&(s.inapp=e.inApp),e.webhook!==void 0&&(s.webhook=e.webhook),Ke(K(s))};export{ot as a,ct as b,Me as c,it as d,Oe as e,De as f,Ke as g,We as r};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/notify",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.113",
|
|
4
4
|
"description": "Multi-channel notifications for Lunora — ctx.notify / ctx.push over @visulima/notification: edge-safe Web Push + FCM, plus chat, in-app inbox and webhook channels, with subscription storage and queue-backed fan-out",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
],
|
|
15
15
|
"homepage": "https://lunora.sh",
|
|
16
16
|
"bugs": "https://github.com/anolilab/lunora/issues",
|
|
17
|
-
"license": "
|
|
17
|
+
"license": "Apache-2.0",
|
|
18
18
|
"author": {
|
|
19
19
|
"name": "Daniel Bannert",
|
|
20
20
|
"email": "d.bannert@anolilab.de"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./evict-oldest-BNXsKx4s.mjs";import{e as c,b as i,c as t,a as h,r as o}from"./providers-BKnOwMJ6.mjs";import"./normalize-B5B9QUol.mjs";export{c as attachResilience,i as buildEngine,t as checkPushTtl,h as checkPushUrgency,o as routingPushProvider};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as P}from"@lunora/errors";import{b as R,c as B,a as L,d as U}from"./providers-BKnOwMJ6.mjs";import{memorySubscriptionStore as W}from"./memorySubscriptionStore-Ccr3ErTV.mjs";import{n as j,t as G,i as Q}from"./normalize-B5B9QUol.mjs";const Z=250,p=(s,c)=>typeof s=="function"?s(c):s,S=s=>s.successful?void 0:s.errorMessages.join("; "),q=(s,c,d)=>s.successful?"accepted":Q(c,d)?"gone":"failed",H=async(s,c,d)=>{const u=Array.from({length:s.length});let g=0;const w=async()=>{for(;g<s.length;){const f=g;g+=1,u[f]=await d(s[f])}};return await Promise.all(Array.from({length:Math.min(c,s.length)},()=>w())),u},C=s=>{B(s.ttl),L(s.urgency),U(s)},J=(s,c)=>({allowedPushOrigins:s.allowedPushOrigins,chat:p(s.chat,c),fcm:p(s.fcm,c),inApp:p(s.inApp,c),webhook:p(s.webhook,c),webPush:p(s.webPush,c)}),I=new WeakMap,K=(s,c)=>{let d=I.get(s);d===void 0&&(d=new WeakMap,I.set(s,d));let u=d.get(c);return u===void 0&&(u={warnedNoPushOriginAllowlist:!1,warnedNoStore:!1},d.set(c,u)),u},oe=(s,c,d={})=>{const u=K(s,c);let g;d.engine===void 0?(u.engine??=R(J(s,c)),g=u.engine):g=d.engine,u.store??=s.store?.(c);let{store:w}=u;w===void 0&&(u.fallbackStore??=W(),!d.silent&&!u.warnedNoStore&&(u.warnedNoStore=!0,console.warn("@lunora/notify: no `store` configured — using a non-durable in-memory subscription store. Configure `store: (env) => d1SubscriptionStore(env.DB)` for production.")),w=u.fallbackStore);const f=w,M=Math.max(1,d.concurrency??s.concurrency??10),b=Math.max(1,d.broadcastPageSize??s.broadcastPageSize??Z),{log:T,metrics:A}=d,m=(e,t,o,n=1)=>{A?.count("notify.send",n,{channel:e,provider:t??e,status:o})},y=(e,t,o)=>{T?.warn(`notify ${e} delivery failed`,{channel:e,provider:t??e,status:"failed",...o})},O=(e,t)=>{A?.count("notify.skipped",1,{channel:e,reason:t})},_=()=>{const e=s.allowedPushOrigins!==void 0&&s.allowedPushOrigins.length>0;d.silent||e||u.warnedNoPushOriginAllowlist||(u.warnedNoPushOriginAllowlist=!0,console.warn("@lunora/notify: Web Push registered without `allowedPushOrigins` — endpoints are guarded by a string classifier at register time and a best-effort DNS re-check at send time, both of which are defeatable. Set `allowedPushOrigins` to the exact push-service origins for a hard guarantee."))},D=async e=>(await f.list(e)).map(({keys:o,token:n,...i})=>i),F=async e=>{if(typeof e!="string")return e;const t=await f.get(e);if(t===void 0)throw new P("BAD_REQUEST",`@lunora/notify: no registered subscription with id "${e}"`);return t},E=async(e,t,{countInline:o,deferStatus:n})=>{let i,l,r;try{i=await g.sendToChannel("push",{...t,to:G(e)}),l=S(i),r=q(i,l,e.kind)}catch(a){r="failed",l=a instanceof Error?a.message:String(a)}if(!n)try{r==="accepted"?await f.markStatus(e.id,"ok"):r==="gone"?await f.delete(e.id):await f.markStatus(e.id,"failed",l)}catch{}return r==="failed"&&y("push",e.kind,{error:l,subscriptionId:e.id,userId:e.userId??null}),o&&m("push",e.kind,r),{error:l,receipt:i,status:r}},$=async(e,t)=>{const o=await H(t,M,async r=>{const{error:a,status:h}=await E(r,e,{countInline:!1,deferStatus:!0});return{error:a,kind:r.kind,status:h,subscription:r}}),n={failed:[],gone:[],ok:[]};for(const{error:r,status:a,subscription:h}of o)a==="accepted"?n.ok.push(h.id):a==="gone"?n.gone.push(h.id):n.failed.push({error:r,id:h.id});try{f.applyOutcomes===void 0?await Promise.all([...n.ok.map(r=>f.markStatus(r,"ok")),...n.failed.map(({error:r,id:a})=>f.markStatus(a,"failed",r)),...n.gone.map(r=>f.delete(r))]):await f.applyOutcomes(n)}catch{}const i=new Map;for(const{kind:r,status:a}of o){const h=`${r} ${a}`,v=i.get(h);v===void 0?i.set(h,{count:1,kind:r,status:a}):v.count+=1}for(const{count:r,kind:a,status:h}of i.values())m("push",a,h,r);const l=o.map(({error:r,status:a,subscription:h})=>a==="accepted"?{id:h.id,status:"ok"}:a==="gone"?{error:r,id:h.id,status:"expired"}:{error:r,id:h.id,status:"failed"});return{failed:l.filter(r=>r.status==="failed").length,outcomes:l,pruned:l.filter(r=>r.status==="expired").length,sent:l.filter(r=>r.status==="ok").length,total:l.length}},N=async(e,t)=>{if(C(e),t?.limit!==void 0&&t.limit<=0)return{nextCursor:void 0,result:{failed:0,outcomes:[],pruned:0,sent:0,total:0}};const o=t?.limit!==void 0&&t.limit>0?Math.trunc(t.limit):void 0,n=o===void 0?b:Math.min(o,b),i=await f.list({after:t?.after,kind:t?.kind,limit:n+1,userId:t?.userId}),l=t?.after===void 0?i:i.filter(z=>z.id>t.after),r=l.length>n,a=r?l.slice(0,n):l;a.length===0&&t?.after===void 0&&O("push","no-subscriptions-matched");const h=await $(e,a);return{nextCursor:r?a[a.length-1]?.id:void 0,result:h}},x={broadcast:async(e,t)=>{const o={failed:0,outcomes:[],pruned:0,sent:0,total:0};let n=t?.after;const i=t?.limit;if(i!==void 0&&i<=0)return o;for(;;){const l=i===void 0?{...t,after:n}:{...t,after:n,limit:i-o.total},{nextCursor:r,result:a}=await N(e,l);if(o.failed+=a.failed,o.pruned+=a.pruned,o.sent+=a.sent,o.total+=a.total,o.outcomes.push(...a.outcomes),i!==void 0&&o.total>=i||r===void 0||r===n)break;n=r}return o},broadcastPage:N,list:e=>D(e),register:e=>("token"in e||_(),f.put(j(e,void 0,{allowedPushOrigins:s.allowedPushOrigins}))),send:async(e,t)=>{C(t);const{error:o,receipt:n}=await E(await F(e),t,{countInline:!0,deferStatus:!1});if(n===void 0)throw new P("INTERNAL",`@lunora/notify: push send failed: ${o??"unknown error"}`);return n},unregister:async(e,t)=>{await f.deleteOwned(e,t.userId??null)}},k=async(e,t)=>{if(g.getProvider(e)===void 0)throw O(e,"channel-not-configured"),new P("BAD_REQUEST",`@lunora/notify: the "${e}" channel is not configured in defineNotify(...)`);const o=await g.sendToChannel(e,t),n=o.successful?"accepted":"failed";return m(e,o.provider,n),n==="failed"&&y(e,o.provider,{error:S(o)}),o};return{notify:{chat:e=>k("chat",e),inApp:e=>k("inapp",e),push:x,send:async e=>{const t=await g.send(e);for(const o of t){const n=o.channel??"unknown",i=o.successful?"accepted":"failed";m(n,o.provider,i),i==="failed"&&y(n,o.provider,{error:S(o)})}return t},webhook:e=>k("webhook",e)},push:x}};export{oe as createNotify};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as u,isLunoraError as L}from"@lunora/errors";import{createNotification as B}from"@visulima/notification";import{retryMiddleware as O}from"@visulima/notification/middleware";import{createFcmProvider as F}from"@visulima/notification/providers/fcm";import{createWebPushProvider as H}from"@visulima/notification/providers/web-push";import{e as G}from"./evict-oldest-BNXsKx4s.mjs";import{a as M,p as k,b as Y,d as j,i as V}from"./normalize-B5B9QUol.mjs";const T=4096,z=e=>typeof e=="string"?e:JSON.stringify(e),J=e=>{const t=e.data===void 0?void 0:Object.fromEntries(Object.entries(e.data).map(([n,s])=>[n,z(s)])),r=new TextEncoder().encode(JSON.stringify({body:e.body,data:t,image:e.imageUrl,title:e.title})).length;if(r>T)throw new u("PAYLOAD_TOO_LARGE",`@lunora/notify: push payload is ${String(r)} bytes; FCM and Web Push accept at most ${String(T)} bytes`)},Q="https://cloudflare-dns.com/dns-query",E=1,I=28,W=2e3,K=(e,t)=>{if(t===E){const r=k(e);return r===void 0||Y(r)}return j(e.toLowerCase())},_=async(e,t,r)=>{try{const n=await fetch(`${Q}?name=${encodeURIComponent(e)}&type=${String(t)}`,{headers:{accept:"application/dns-json"},signal:AbortSignal.timeout(r)});if(!n.ok)return;const s=await n.json();return s.Status===void 0||s.Status===0?s.Answer??[]:[]}catch{return}},q=async(e,t=W)=>{const r=M(e);if(r.includes(":")||k(r)!==void 0)return{kind:"skipped"};const[n,s]=await Promise.all([_(r,E,t),_(r,I,t)]);if(n===void 0||s===void 0)return{kind:"failed"};const o=[...n,...s].filter(i=>i.type===E||i.type===I);for(const i of o)if(K(i.data,i.type))return{address:i.data,kind:"private"};return o.length===0?{kind:"unresolved"}:{kind:"public"}},$=e=>{let t=e;if(typeof e=="string"){if(!e.startsWith("{"))return;try{t=JSON.parse(e)}catch{return}}const r=t?.endpoint;return typeof r=="string"?r:void 0},x=e=>$(e)===void 0?"fcm":"web-push",h="lunora-push-router",y=new Map,X=256,Z=async(e,t)=>{if(t!==void 0&&t.length>0)return;let r;try{({hostname:r}=new URL(e))}catch{return}const n=y.get(r),s=n??q(r),o=await s;if(n===void 0&&(o.kind==="private"||o.kind==="public")&&(G(y,X),y.set(r,s)),o.kind==="private")throw new u("FORBIDDEN",`@lunora/notify: web-push endpoint host "${r}" resolves to a private/internal address (${o.address}); refusing to send (DNS-rebinding guard)`);if(o.kind==="unresolved")throw new u("FORBIDDEN",`@lunora/notify: web-push endpoint host "${r}" did not resolve to any address; refusing to send (DNS-rebinding guard)`);if(o.kind==="failed")throw new u("FORBIDDEN",`@lunora/notify: could not verify where web-push endpoint host "${r}" resolves (the DNS-over-HTTPS lookup failed); refusing to send (DNS-rebinding guard)`)},ee=(e,t)=>{const r=[e.provider,t.provider].filter(s=>s!==void 0),n=[...e.recipients??[],...t.recipients??[]];return{...e,messageId:[e.messageId,t.messageId].join(","),response:[e.response,t.response],sent:e.sent&&t.sent,timestamp:new Date(Math.max(e.timestamp.getTime(),t.timestamp.getTime())),...r.length>0?{provider:r.join(",")}:{},...n.length>0?{recipients:n}:{}}},N=e=>e instanceof Error?e.message:typeof e=="string"?e:void 0,C="PUSH_PARTIALLY_DELIVERED",U=e=>L(e)&&e.code===C,te=e=>{if(!U(e))return;const{data:t}=e;return t==="fcm"||t==="web-push"?t:void 0},m=(e,t)=>{if(!e.success||!t.success){if(e.success||t.success){const[n,s]=e.success?["web-push","fcm"]:["fcm","web-push"],o=e.success?t.error:e.error;return{error:new u(C,`@lunora/notify: push partially delivered — the ${n} group was accepted, the ${s} group failed and re-attempting it did not recover it (${N(o)??"unknown error"}). The whole send is not retried: that would re-send to the ${n} targets that already received it. Re-send to the ${s} targets only.`,{cause:o,data:s}),success:!1}}return{error:new AggregateError([e.error,t.error],"@lunora/notify: both push target groups failed"),success:!1}}const r=e.data===void 0||t.data===void 0?e.data??t.data:ee(e.data,t.data);return r===void 0?{success:!0}:{data:r,success:!0}},v=e=>V(N(e)),l=5,re=3e4,se=e=>{if(e.provider!==h)return[e.provider];const{to:t}=e.payload,r=Array.isArray(t)?t:[t],n=new Set(r.map(s=>x(s)));return n.size===0?[e.provider]:[...n].map(s=>`${e.provider}:${s}`)},ne=(e,t)=>e.failures>=l&&t-e.openedAt<re,oe=(e,t,r)=>{const n=te(e),s=n===void 0?void 0:`${h}:${n}`,o=s!==void 0&&t.includes(s);for(const[i,a]of r.entries())o&&t[i]!==s?a.failures=0:(a.failures+=1,a.failures>=l&&(a.openedAt=Date.now()))},ie=()=>{const e=new Map,t=r=>{const n=e.get(r);if(n!==void 0)return n;const s={failures:0,openedAt:0};return e.set(r,s),s};return async(r,n)=>{const s=se(r),o=s.map(d=>t(d)),i=Date.now();if(o.every(d=>ne(d,i)))return{error:new u("SERVICE_UNAVAILABLE",`@lunora/notify: circuit open for "${s.join('", "')}" after ${l.toString()} consecutive failures`),success:!1};for(const d of o)d.failures>=l&&(d.failures=l-1);const a=await n(r);if(a.success)for(const d of o)d.failures=0;else v(a.error)||oe(a.error,s,o);return a}},ae=2,b=async(e,t)=>{try{return await e.send(t)}catch(r){return{error:r,success:!1}}},ce=new Set(["high","low","normal","very-low"]),de=e=>ce.has(e),me=e=>{if(e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0))throw new u("BAD_REQUEST",`@lunora/notify: push ttl must be a non-negative integer number of seconds, got ${typeof e=="number"?String(e):typeof e}`);return e},be=e=>{if(e!==void 0&&!de(e))throw new u("BAD_REQUEST",`@lunora/notify: push urgency must be "very-low", "low", "normal" or "high", got ${JSON.stringify(e)}`)},ue=e=>{const t=O({baseDelay:e.retryBaseDelay,retries:ae,shouldRetry:s=>!v(s)}),r=async(s,o,i)=>v(i.error)?i:t({channel:"push",payload:o,provider:h},async a=>b(s,a.payload)),n=s=>{const o=s===void 0?e.fcm:e.webPush;if(o===void 0)throw new Error(s===void 0?"@lunora/notify: received an FCM token target but no `fcm` channel is configured":"@lunora/notify: received a web-push target but no `webPush` channel is configured");return o};return{channel:"push",id:h,initialize:async()=>{await e.webPush?.initialize(),await e.fcm?.initialize()},isAvailable:()=>(e.webPush??e.fcm)!==void 0,send:async s=>{const o=Array.isArray(s.to)?s.to:[s.to];if(o.length===0)throw new u("BAD_REQUEST","@lunora/notify: push send has no recipients — `to` is an empty array");J(s);const i=o.map(c=>$(c));for(const c of i)c!==void 0&&await Z(c,e.allowedPushOrigins);const a=o.filter((c,w)=>i[w]!==void 0),d=o.filter((c,w)=>i[w]===void 0),g=i.find(c=>c!==void 0);if(d.length===0&&g!==void 0)return n(g).send(s);if(a.length===0)return n(void 0).send(s);const R=c=>({...s,to:c.length===1&&c[0]!==void 0?c[0]:c}),P=n(g),S=n(void 0),D=R(a),A=R(d),[f,p]=await Promise.all([b(P,D),b(S,A)]);return f.success&&!p.success?m(f,await r(S,A,p)):p.success&&!f.success?m(await r(P,D,f),p):m(f,p)}}},fe=(e,t={})=>e.use(O({baseDelay:t.retryBaseDelay,shouldRetry:r=>!v(r)&&!U(r)})).use(ie()),Ee=e=>{const t=e.webPush===void 0?void 0:H(e.webPush),r=e.fcm===void 0?void 0:F(e.fcm),n={};return(t!==void 0||r!==void 0)&&(n.push=ue({allowedPushOrigins:e.allowedPushOrigins,fcm:r,webPush:t})),e.chat!==void 0&&(n.chat=e.chat),e.inApp!==void 0&&(n.inapp=e.inApp),e.webhook!==void 0&&(n.webhook=e.webhook),fe(B(n))};export{be as a,Ee as b,me as c,J as d,fe as e,ue as r};
|