@lunora/notify 1.0.0-alpha.110 → 1.0.0-alpha.111
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -3
- package/dist/index.d.mts +14 -7
- package/dist/index.d.ts +14 -7
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/FCM_ENV_KEYS-DyR2MZ31.mjs +2 -0
- package/dist/packem_shared/base64-C6eVduy0.mjs +1 -0
- package/dist/packem_shared/buildEngine-D6jKHClU.mjs +1 -0
- package/dist/packem_shared/createNotify-Bfgf4YrZ.mjs +1 -0
- package/dist/packem_shared/evict-oldest-BNXsKx4s.mjs +1 -0
- package/dist/packem_shared/providers-BKnOwMJ6.mjs +1 -0
- package/dist/web.mjs +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/FCM_ENV_KEYS-BbhPScGH.mjs +0 -1
- package/dist/packem_shared/buildEngine-x7r_sr3M.mjs +0 -1
- package/dist/packem_shared/createNotify-hH_Y5OJQ.mjs +0 -1
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ import { defineNotify, webPushFromEnv, fcmFromEnv, d1SubscriptionStore } from "@
|
|
|
17
17
|
|
|
18
18
|
export default defineNotify({
|
|
19
19
|
webPush: (env) => webPushFromEnv(env), // reads VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY / VAPID_SUBJECT
|
|
20
|
-
fcm: (env) => fcmFromEnv(env), // reads
|
|
20
|
+
fcm: (env) => fcmFromEnv(env), // reads FCM_SERVICE_ACCOUNT (+ optional FCM_PROJECT_ID)
|
|
21
21
|
store: (env) => d1SubscriptionStore(env.DB),
|
|
22
22
|
});
|
|
23
23
|
```
|
|
@@ -28,10 +28,14 @@ export default defineNotify({
|
|
|
28
28
|
VAPID_PUBLIC_KEY=<your-vapid-public-key>
|
|
29
29
|
VAPID_PRIVATE_KEY=<your-vapid-private-key>
|
|
30
30
|
VAPID_SUBJECT=mailto:you@example.com
|
|
31
|
-
|
|
32
|
-
FCM_ACCESS_TOKEN=<your-fcm-access-token>
|
|
31
|
+
FCM_SERVICE_ACCOUNT=<base64-of-your-service-account-key-json>
|
|
33
32
|
```
|
|
34
33
|
|
|
34
|
+
`.dev.vars` cannot hold the JSON's quotes, so store the key file base64-encoded:
|
|
35
|
+
`lunora env set FCM_SERVICE_ACCOUNT "$(base64 < key.json | tr -d '\n')"`. In production
|
|
36
|
+
the raw JSON works too: `wrangler secret put FCM_SERVICE_ACCOUNT < key.json`.
|
|
37
|
+
`FCM_PROJECT_ID` is optional and overrides the key file's `project_id`.
|
|
38
|
+
|
|
35
39
|
Generate a VAPID keypair once: `npx web-push generate-vapid-keys`.
|
|
36
40
|
|
|
37
41
|
## Register a device (browser)
|
package/dist/index.d.mts
CHANGED
|
@@ -519,6 +519,7 @@ declare const WEB_PUSH_ENV_KEYS: {
|
|
|
519
519
|
declare const FCM_ENV_KEYS: {
|
|
520
520
|
readonly accessToken: "FCM_ACCESS_TOKEN";
|
|
521
521
|
readonly projectId: "FCM_PROJECT_ID";
|
|
522
|
+
readonly serviceAccount: "FCM_SERVICE_ACCOUNT";
|
|
522
523
|
};
|
|
523
524
|
/**
|
|
524
525
|
* Resolve a {@link WebPushConfig} from the Worker `env` VAPID secrets
|
|
@@ -531,13 +532,19 @@ declare const FCM_ENV_KEYS: {
|
|
|
531
532
|
*/
|
|
532
533
|
declare const webPushFromEnv: (env: NotifyEnv, overrides?: Partial<WebPushConfig>) => WebPushConfig | undefined;
|
|
533
534
|
/**
|
|
534
|
-
* Resolve an {@link FcmConfig} from the Worker `env
|
|
535
|
-
* static `FCM_ACCESS_TOKEN`). Returns `undefined` when the project id is missing.
|
|
535
|
+
* Resolve an {@link FcmConfig} from the Worker `env`.
|
|
536
536
|
*
|
|
537
|
-
*
|
|
538
|
-
*
|
|
539
|
-
* `defineNotify({ fcm: (env) =>
|
|
540
|
-
*
|
|
537
|
+
* Production: `FCM_SERVICE_ACCOUNT` holds the Google service-account key file, as JSON or
|
|
538
|
+
* base64 of it. The access token is minted from it on demand and cached until shortly
|
|
539
|
+
* before it expires, so `defineNotify({ fcm: (env) => fcmFromEnv(env) })` is correct as written.
|
|
540
|
+
* `FCM_PROJECT_ID` overrides the project id in the key file.
|
|
541
|
+
*
|
|
542
|
+
* Dev: a static `FCM_ACCESS_TOKEN` is accepted when no service account is set. It
|
|
543
|
+
* expires within the hour, so it is only a stopgap for local work.
|
|
544
|
+
*
|
|
545
|
+
* Returns `undefined` when no project id can be resolved. A malformed key does not throw
|
|
546
|
+
* here: the token source rejects with the parse error instead, so only FCM sends fail, not
|
|
547
|
+
* the other channels that share this engine.
|
|
541
548
|
*/
|
|
542
549
|
declare const fcmFromEnv: (env: NotifyEnv, overrides?: Partial<FcmConfig>) => FcmConfig | undefined;
|
|
543
550
|
/**
|
|
@@ -553,7 +560,7 @@ declare const fcmFromEnv: (env: NotifyEnv, overrides?: Partial<FcmConfig>) => Fc
|
|
|
553
560
|
*
|
|
554
561
|
* export default defineNotify({
|
|
555
562
|
* webPush: (env) => webPushFromEnv(env), // VAPID_* from .dev.vars
|
|
556
|
-
* fcm: (env) => fcmFromEnv(env), //
|
|
563
|
+
* fcm: (env) => fcmFromEnv(env), // FCM_SERVICE_ACCOUNT (+ FCM_PROJECT_ID)
|
|
557
564
|
* store: (env) => d1SubscriptionStore(env.DB),
|
|
558
565
|
* });
|
|
559
566
|
* ```
|
package/dist/index.d.ts
CHANGED
|
@@ -519,6 +519,7 @@ declare const WEB_PUSH_ENV_KEYS: {
|
|
|
519
519
|
declare const FCM_ENV_KEYS: {
|
|
520
520
|
readonly accessToken: "FCM_ACCESS_TOKEN";
|
|
521
521
|
readonly projectId: "FCM_PROJECT_ID";
|
|
522
|
+
readonly serviceAccount: "FCM_SERVICE_ACCOUNT";
|
|
522
523
|
};
|
|
523
524
|
/**
|
|
524
525
|
* Resolve a {@link WebPushConfig} from the Worker `env` VAPID secrets
|
|
@@ -531,13 +532,19 @@ declare const FCM_ENV_KEYS: {
|
|
|
531
532
|
*/
|
|
532
533
|
declare const webPushFromEnv: (env: NotifyEnv, overrides?: Partial<WebPushConfig>) => WebPushConfig | undefined;
|
|
533
534
|
/**
|
|
534
|
-
* Resolve an {@link FcmConfig} from the Worker `env
|
|
535
|
-
* static `FCM_ACCESS_TOKEN`). Returns `undefined` when the project id is missing.
|
|
535
|
+
* Resolve an {@link FcmConfig} from the Worker `env`.
|
|
536
536
|
*
|
|
537
|
-
*
|
|
538
|
-
*
|
|
539
|
-
* `defineNotify({ fcm: (env) =>
|
|
540
|
-
*
|
|
537
|
+
* Production: `FCM_SERVICE_ACCOUNT` holds the Google service-account key file, as JSON or
|
|
538
|
+
* base64 of it. The access token is minted from it on demand and cached until shortly
|
|
539
|
+
* before it expires, so `defineNotify({ fcm: (env) => fcmFromEnv(env) })` is correct as written.
|
|
540
|
+
* `FCM_PROJECT_ID` overrides the project id in the key file.
|
|
541
|
+
*
|
|
542
|
+
* Dev: a static `FCM_ACCESS_TOKEN` is accepted when no service account is set. It
|
|
543
|
+
* expires within the hour, so it is only a stopgap for local work.
|
|
544
|
+
*
|
|
545
|
+
* Returns `undefined` when no project id can be resolved. A malformed key does not throw
|
|
546
|
+
* here: the token source rejects with the parse error instead, so only FCM sends fail, not
|
|
547
|
+
* the other channels that share this engine.
|
|
541
548
|
*/
|
|
542
549
|
declare const fcmFromEnv: (env: NotifyEnv, overrides?: Partial<FcmConfig>) => FcmConfig | undefined;
|
|
543
550
|
/**
|
|
@@ -553,7 +560,7 @@ declare const fcmFromEnv: (env: NotifyEnv, overrides?: Partial<FcmConfig>) => Fc
|
|
|
553
560
|
*
|
|
554
561
|
* export default defineNotify({
|
|
555
562
|
* webPush: (env) => webPushFromEnv(env), // VAPID_* from .dev.vars
|
|
556
|
-
* fcm: (env) => fcmFromEnv(env), //
|
|
563
|
+
* fcm: (env) => fcmFromEnv(env), // FCM_SERVICE_ACCOUNT (+ FCM_PROJECT_ID)
|
|
557
564
|
* store: (env) => d1SubscriptionStore(env.DB),
|
|
558
565
|
* });
|
|
559
566
|
* ```
|
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
|
|
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-Bfgf4YrZ.mjs";import{b as E,r as d}from"./packem_shared/providers-BKnOwMJ6.mjs";import{enqueuePushBroadcast as P,runPushBroadcastPage as c}from"./packem_shared/enqueuePushBroadcast-C9tO0BZj.mjs";import{d1SubscriptionStore as b}from"./packem_shared/d1SubscriptionStore-B13P2ERZ.mjs";import{memorySubscriptionStore as h}from"./packem_shared/memorySubscriptionStore-Ccr3ErTV.mjs";import{f as _,i as y,n as v,t as w,w as B}from"./packem_shared/normalize-B5B9QUol.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,2 @@
|
|
|
1
|
+
import{a as y,t as d}from"./base64-C6eVduy0.mjs";import{e as S}from"./evict-oldest-BNXsKx4s.mjs";const l="https://oauth2.googleapis.com/token",g="https://www.googleapis.com/auth/firebase.messaging",f=3600,T=6e4,m=1e4,A=16,p=new Map,h=e=>{const o=e.trim();return o.startsWith("{")?o:new TextDecoder().decode(y(o))},E=e=>{let o;try{o=JSON.parse(h(e))}catch{throw new TypeError("FCM_SERVICE_ACCOUNT is neither valid JSON nor base64-encoded JSON (use the service-account key file as-is, or base64 of it)")}const t=o;if(typeof t?.client_email!="string"||typeof t.private_key!="string")throw new TypeError("FCM_SERVICE_ACCOUNT must contain client_email and private_key");return{client_email:t.client_email,private_key:t.private_key.replaceAll(String.raw`\n`,`
|
|
2
|
+
`),project_id:typeof t.project_id=="string"&&t.project_id!==""?t.project_id:void 0}},v=e=>{const o=y(e.replaceAll(/-----[^-]+-----|\s/g,""));return crypto.subtle.importKey("pkcs8",o,{hash:"SHA-256",name:"RSASSA-PKCS1-v1_5"},!1,["sign"])},C=async(e,o)=>{const t=new TextEncoder,n=d(t.encode(JSON.stringify({alg:"RS256",typ:"JWT"}))),r=d(t.encode(JSON.stringify(e))),c=await crypto.subtle.sign("RSASSA-PKCS1-v1_5",o,t.encode(`${n}.${r}`));return`${n}.${r}.${d(new Uint8Array(c))}`},I=async(e,o,t)=>{const n=await v(e.private_key),r=Math.floor(t()/1e3),c=await C({aud:l,exp:r+f,iat:r,iss:e.client_email,scope:g},n),i=await o(l,{body:new URLSearchParams({assertion:c,grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer"}),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST",signal:AbortSignal.timeout(m)});if(!i.ok)throw new Error(`Google token exchange failed with HTTP ${String(i.status)}`);const s=await i.json();if(typeof s.access_token!="string"||typeof s.expires_in!="number")throw new TypeError("Google token exchange returned no access_token");return{expiresAt:t()+s.expires_in*1e3-T,token:s.access_token}},w=(e,o={})=>{const t=o.fetch??fetch,n=o.now??Date.now;return()=>{const r=p.get(e);if(r!==void 0&&r.expiresAt>n())return r.token;r===void 0&&S(p,A);const c=async()=>I(E(e),t,n),i={expiresAt:Number.POSITIVE_INFINITY,token:c().then(s=>(i.expiresAt=s.expiresAt,s.token),s=>{throw p.get(e)===i&&p.delete(e),s})};return p.set(e,i),i.token}},_={privateKey:"VAPID_PRIVATE_KEY",publicKey:"VAPID_PUBLIC_KEY",subject:"VAPID_SUBJECT"},u={accessToken:"FCM_ACCESS_TOKEN",projectId:"FCM_PROJECT_ID",serviceAccount:"FCM_SERVICE_ACCOUNT"},a=(e,o)=>{const t=e[o];return typeof t=="string"&&t!==""?t:void 0},j=(e,o)=>{const t=a(e,_.publicKey),n=a(e,_.privateKey),r=a(e,_.subject);if(!(t===void 0||n===void 0||r===void 0))return{vapidPrivateKey:n,vapidPublicKey:t,vapidSubject:r,...o}},k="unresolved-malformed-service-account",O=e=>{try{return E(e).project_id}catch{return k}},K=(e,o)=>{const t=a(e,u.projectId),n=a(e,u.serviceAccount),c=(o?.projectId===""?void 0:o?.projectId)??t??(n===void 0?void 0:O(n));if(c!==void 0)return n!==void 0?{getAccessToken:w(n),...o,projectId:c}:{accessToken:a(e,u.accessToken),...o,projectId:c}};export{u as FCM_ENV_KEYS,_ as WEB_PUSH_ENV_KEYS,K as fcmFromEnv,j as webPushFromEnv};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const l=r=>{const n=atob(r),t=new Uint8Array(n.length);for(let c=0;c<n.length;c+=1)t[c]=n.codePointAt(c)??0;return t},e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",s=r=>{let n="",t=0;const c=r.length-2;for(;t<c;t+=3){const a=r[t]<<16|r[t+1]<<8|r[t+2];n+=e.charAt(a>>18&63)+e.charAt(a>>12&63)+e.charAt(a>>6&63)+e.charAt(a&63)}const o=r.length-t;if(o===1){const a=r[t]<<16;n+=e.charAt(a>>18&63)+e.charAt(a>>12&63)}else if(o===2){const a=r[t]<<16|r[t+1]<<8;n+=e.charAt(a>>18&63)+e.charAt(a>>12&63)+e.charAt(a>>6&63)}return n},A=r=>{const n=r.replaceAll("-","+").replaceAll("_","/"),t=n+"=".repeat((4-n.length%4)%4);return l(t)};export{l as a,A as f,s as t};
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const i=(e,s)=>{if(e.size<s)return;const t=e.keys().next().value;t!==void 0&&e.delete(t)};export{i as e};
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
package/dist/web.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{f as v}from"./packem_shared/base64-C6eVduy0.mjs";const p=3e4,c="@lunora/notify: the registered service worker never became active",u=r=>v(r),w=(r,e)=>r.length===e.length&&r.every((i,t)=>i===e[t]),b=(r,e)=>{const i=r.options.applicationServerKey;return i===null?!1:w(new Uint8Array(i),u(e))},o=globalThis,l=()=>o.navigator?.serviceWorker!==void 0&&o.PushManager!==void 0&&o.Notification!==void 0,g=async()=>{const r=await navigator.serviceWorker.getRegistration();return r?.active!==null?r:await new Promise((e,i)=>{const t=setTimeout(()=>{i(new Error(c))},p);navigator.serviceWorker.ready.then(s=>(clearTimeout(t),e(s),s)).catch(s=>{clearTimeout(t),i(s instanceof Error?s:new Error(String(s)))})})},h=async r=>{if(!l())throw new Error("@lunora/notify: Web Push is not supported in this browser (needs service workers + PushManager + Notification)");let e;if(r.serviceWorkerUrl===void 0){const n=await g();if(n===void 0)throw new Error("@lunora/notify: no service worker is registered for this page — register one first, or pass `serviceWorkerUrl`");e=n}else{const n=r.scope===void 0?void 0:{scope:r.scope};e=await navigator.serviceWorker.register(r.serviceWorkerUrl,n)}const i=await Notification.requestPermission();if(i!=="granted")throw new Error(`@lunora/notify: notification permission was not granted (got "${i}")`);const t=await e.pushManager.getSubscription();let s=null,a;t!==null&&(b(t,r.vapidPublicKey)?s=t:(a=t.endpoint,await t.unsubscribe()));const f=s??await e.pushManager.subscribe({applicationServerKey:u(r.vapidPublicKey),userVisibleOnly:!0});return{replacedEndpoint:a,subscription:f.toJSON()}},y=async()=>{if(!l())return!1;let r;try{r=await g()}catch(i){if(i instanceof Error&&i.message===c)return!1;throw i}if(r===void 0)return!1;const e=await r.pushManager.getSubscription();return e===null?!1:e.unsubscribe()};export{p as READY_WAIT_TIMEOUT_MS,l as isPushSupported,h as subscribeToPush,y as unsubscribeFromPush};
|
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.111",
|
|
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",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const r={privateKey:"VAPID_PRIVATE_KEY",publicKey:"VAPID_PUBLIC_KEY",subject:"VAPID_SUBJECT"},i={accessToken:"FCM_ACCESS_TOKEN",projectId:"FCM_PROJECT_ID"},t=(c,o)=>{const e=c[o];return typeof e=="string"&&e!==""?e:void 0},d=(c,o)=>{const e=t(c,r.publicKey),s=t(c,r.privateKey),n=t(c,r.subject);if(!(e===void 0||s===void 0||n===void 0))return{vapidPrivateKey:s,vapidPublicKey:e,vapidSubject:n,...o}},E=(c,o)=>{const e=t(c,i.projectId);return e===void 0?void 0:{accessToken:t(c,i.accessToken),projectId:e,...o}};export{i as FCM_ENV_KEYS,r as WEB_PUSH_ENV_KEYS,E as fcmFromEnv,d as webPushFromEnv};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as d,isLunoraError as U}from"@lunora/errors";import{createNotification as L}from"@visulima/notification";import{retryMiddleware as _}from"@visulima/notification/middleware";import{createFcmProvider as B}from"@visulima/notification/providers/fcm";import{createWebPushProvider as H}from"@visulima/notification/providers/web-push";import{a as F,p as k,b as G,d as M,i as z}from"./normalize-B5B9QUol.mjs";const V=(e,t)=>{if(e.size<t)return;const r=e.keys().next().value;r!==void 0&&e.delete(r)},j="https://cloudflare-dns.com/dns-query",E=1,A=28,Y=2e3,Q=(e,t)=>{if(t===E){const r=k(e);return r===void 0||G(r)}return M(e.toLowerCase())},I=async(e,t,r)=>{try{const s=await fetch(`${j}?name=${encodeURIComponent(e)}&type=${String(t)}`,{headers:{accept:"application/dns-json"},signal:AbortSignal.timeout(r)});if(!s.ok)return;const n=await s.json();return n.Status===void 0||n.Status===0?n.Answer??[]:[]}catch{return}},J=async(e,t=Y)=>{const r=F(e);if(r.includes(":")||k(r)!==void 0)return{kind:"skipped"};const[s,n]=await Promise.all([I(r,E,t),I(r,A,t)]);if(s===void 0||n===void 0)return{kind:"failed"};const o=[...s,...n].filter(i=>i.type===E||i.type===A);for(const i of o)if(Q(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},K=e=>$(e)===void 0?"fcm":"web-push",h="lunora-push-router",y=new Map,W=256,q=async(e,t)=>{if(t!==void 0&&t.length>0)return;let r;try{({hostname:r}=new URL(e))}catch{return}const s=y.get(r),n=s??J(r),o=await n;if(s===void 0&&(o.kind==="private"||o.kind==="public")&&(V(y,W),y.set(r,n)),o.kind==="private")throw new d("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 d("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 d("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)`)},x=(e,t)=>{const r=[e.provider,t.provider].filter(n=>n!==void 0),s=[...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(",")}:{},...s.length>0?{recipients:s}:{}}},O=e=>e instanceof Error?e.message:typeof e=="string"?e:void 0,N="PUSH_PARTIALLY_DELIVERED",C=e=>U(e)&&e.code===N,X=e=>{if(!C(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[s,n]=e.success?["web-push","fcm"]:["fcm","web-push"],o=e.success?t.error:e.error;return{error:new d(N,`@lunora/notify: push partially delivered — the ${s} group was accepted, the ${n} 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 ${s} targets that already received it. Re-send to the ${n} targets only.`,{cause:o,data:n}),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:x(e.data,t.data);return r===void 0?{success:!0}:{data:r,success:!0}},v=e=>z(O(e)),p=5,Z=3e4,ee=e=>{if(e.provider!==h)return[e.provider];const{to:t}=e.payload,r=Array.isArray(t)?t:[t],s=new Set(r.map(n=>K(n)));return s.size===0?[e.provider]:[...s].map(n=>`${e.provider}:${n}`)},te=(e,t)=>e.failures>=p&&t-e.openedAt<Z,re=(e,t,r)=>{const s=X(e),n=s===void 0?void 0:`${h}:${s}`,o=n!==void 0&&t.includes(n);for(const[i,a]of r.entries())o&&t[i]!==n?a.failures=0:(a.failures+=1,a.failures>=p&&(a.openedAt=Date.now()))},ne=()=>{const e=new Map,t=r=>{const s=e.get(r);if(s!==void 0)return s;const n={failures:0,openedAt:0};return e.set(r,n),n};return async(r,s)=>{const n=ee(r),o=n.map(u=>t(u)),i=Date.now();if(o.every(u=>te(u,i)))return{error:new d("SERVICE_UNAVAILABLE",`@lunora/notify: circuit open for "${n.join('", "')}" after ${p.toString()} consecutive failures`),success:!1};for(const u of o)u.failures>=p&&(u.failures=p-1);const a=await s(r);if(a.success)for(const u of o)u.failures=0;else v(a.error)||re(a.error,n,o);return a}},se=2,b=async(e,t)=>{try{return await e.send(t)}catch(r){return{error:r,success:!1}}},oe=new Set(["high","low","normal","very-low"]),ie=e=>oe.has(e),ve=e=>{if(e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0))throw new d("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},we=e=>{if(e!==void 0&&!ie(e))throw new d("BAD_REQUEST",`@lunora/notify: push urgency must be "very-low", "low", "normal" or "high", got ${JSON.stringify(e)}`)},ae=e=>{const t=_({baseDelay:e.retryBaseDelay,retries:se,shouldRetry:n=>!v(n)}),r=async(n,o,i)=>v(i.error)?i:t({channel:"push",payload:o,provider:h},async a=>b(n,a.payload)),s=n=>{const o=n===void 0?e.fcm:e.webPush;if(o===void 0)throw new Error(n===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 n=>{const o=Array.isArray(n.to)?n.to:[n.to];if(o.length===0)throw new d("BAD_REQUEST","@lunora/notify: push send has no recipients — `to` is an empty array");const i=o.map(c=>$(c));for(const c of i)c!==void 0&&await q(c,e.allowedPushOrigins);const a=o.filter((c,g)=>i[g]!==void 0),u=o.filter((c,g)=>i[g]===void 0),w=i.find(c=>c!==void 0);if(u.length===0&&w!==void 0)return s(w).send(n);if(a.length===0)return s(void 0).send(n);const R=c=>({...n,to:c.length===1&&c[0]!==void 0?c[0]:c}),D=s(w),P=s(void 0),S=R(a),T=R(u),[f,l]=await Promise.all([b(D,S),b(P,T)]);return f.success&&!l.success?m(f,await r(P,T,l)):l.success&&!f.success?m(await r(D,S,f),l):m(f,l)}}},ce=(e,t={})=>e.use(_({baseDelay:t.retryBaseDelay,shouldRetry:r=>!v(r)&&!C(r)})).use(ne()),ge=e=>{const t=e.webPush===void 0?void 0:H(e.webPush),r=e.fcm===void 0?void 0:B(e.fcm),s={};return(t!==void 0||r!==void 0)&&(s.push=ae({allowedPushOrigins:e.allowedPushOrigins,fcm:r,webPush:t})),e.chat!==void 0&&(s.chat=e.chat),e.inApp!==void 0&&(s.inapp=e.inApp),e.webhook!==void 0&&(s.webhook=e.webhook),ce(L(s))};export{ce as attachResilience,ge as buildEngine,ve as checkPushTtl,we as checkPushUrgency,ae as routingPushProvider};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{buildEngine as B,checkPushTtl as C,checkPushUrgency as I}from"./buildEngine-x7r_sr3M.mjs";import{memorySubscriptionStore as L}from"./memorySubscriptionStore-Ccr3ErTV.mjs";import{n as U,t as W,i as j}from"./normalize-B5B9QUol.mjs";const G=250,p=(s,c)=>typeof s=="function"?s(c):s,P=s=>s.successful?void 0:s.errorMessages.join("; "),Q=(s,c,d)=>s.successful?"accepted":j(c,d)?"gone":"failed",Z=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},q=(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)}),M=new WeakMap,H=(s,c)=>{let d=M.get(s);d===void 0&&(d=new WeakMap,M.set(s,d));let u=d.get(c);return u===void 0&&(u={warnedNoPushOriginAllowlist:!1,warnedNoStore:!1},d.set(c,u)),u},te=(s,c,d={})=>{const u=H(s,c);let g;d.engine===void 0?(u.engine??=B(q(s,c)),g=u.engine):g=d.engine,u.store??=s.store?.(c);let{store:w}=u;w===void 0&&(u.fallbackStore??=L(),!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,T=Math.max(1,d.concurrency??s.concurrency??10),b=Math.max(1,d.broadcastPageSize??s.broadcastPageSize??G),{log:_,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)=>{_?.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})},D=()=>{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."))},$=async e=>(await f.list(e)).map(({keys:o,token:n,...i})=>i),z=async e=>{if(typeof e!="string")return e;const t=await f.get(e);if(t===void 0)throw new S("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:W(e)}),l=P(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}},F=async(e,t)=>{const o=await Z(t,T,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.ttl),I(e.urgency),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(R=>R.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 F(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=>$(e),register:e=>("token"in e||D(),f.put(U(e,void 0,{allowedPushOrigins:s.allowedPushOrigins}))),send:async(e,t)=>{C(t.ttl),I(t.urgency);const{error:o,receipt:n}=await E(await z(e),t,{countInline:!0,deferStatus:!1});if(n===void 0)throw new S("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 S("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:P(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:P(o)})}return t},webhook:e=>k("webhook",e)},push:x}};export{te as createNotify};
|