@stacksjs/notifications 0.70.229 → 0.70.230

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ import type { NotificationChannel, NotificationPayload, NotificationRecipient, NotifyOptions, NotifyResult } from './index';
2
+ export declare function resolveDeliveryRecipient(recipient: NotificationRecipient, channel: NotificationChannel): string;
3
+ export declare function makeDeliveryRecord(recipient: NotificationRecipient, payload: NotificationPayload, result: NotifyResult, options: NotifyOptions, sentAt?: unknown): NotificationDeliveryRecord;
4
+ export declare function recordNotificationDelivery(record: NotificationDeliveryRecord): Promise<void>;
5
+ export declare interface NotificationDeliveryRecord {
6
+ userId?: number
7
+ channel: NotificationChannel
8
+ recipient: string
9
+ subject?: string
10
+ body: string
11
+ status: 'sent' | 'failed'
12
+ error?: string
13
+ metadata?: Record<string, unknown>
14
+ sentAt: string
15
+ }
package/dist/index.d.ts CHANGED
@@ -2,10 +2,13 @@ import { BroadcastNotificationDriver } from './drivers/broadcast';
2
2
  import { chat, email, push, sms } from './drivers/index';
3
3
  import { DatabaseNotificationDriver } from './drivers/database';
4
4
  import { filterChannelsByPreferences } from './preferences';
5
+ import { makeDeliveryRecord, recordNotificationDelivery } from './delivery';
5
6
  import type { EmailMessage, EmailResult } from '@stacksjs/types';
6
7
  export type { BroadcastNotificationOptions, BroadcastNotificationResult } from './drivers/broadcast';
8
+ export type { NotificationDeliveryRecord } from './delivery';
7
9
  export type { CreateNotificationOptions, DatabaseNotification } from './drivers/database';
8
10
  export type { NotificationPreferenceRow, PreferenceChannel } from './preferences';
11
+ export declare function ensureSuccessfulEmailResult(result: EmailResult): void;
9
12
  export declare function useChat(driver?: string): typeof chat[keyof typeof chat];
10
13
  /**
11
14
  * Return the email transport — by default the @stacksjs/email Mail
@@ -75,6 +78,7 @@ export declare interface NotifyResult {
75
78
  }
76
79
  export type NotificationChannel = 'email' | 'sms' | 'chat' | 'database' | 'push' | 'broadcast';
77
80
  export { BroadcastNotificationDriver } from './drivers/broadcast';
81
+ export { makeDeliveryRecord, recordNotificationDelivery, resolveDeliveryRecipient } from './delivery';
78
82
  export { DatabaseNotificationDriver } from './drivers/database';
79
83
  export {
80
84
  bulkSetPreferences,
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- var P=import.meta.require;import{log as _}from"@stacksjs/cli";import{notification as m}from"@stacksjs/config";import{mail as q}from"@stacksjs/email";import{log as x}from"@stacksjs/cli";var W={async send(z){let F=z.event??"notification",J=z.channel;if(!J)J=z.userId!==void 0?`private-user-${z.userId}`:"notifications";try{let G=await import("@stacksjs/realtime").catch(()=>null),K=G?.emit,O=G?.getServer;if(!K||!O)return{delivered:!1,channel:J,event:F,reason:"@stacksjs/realtime is not available"};if(!O())return{delivered:!1,channel:J,event:F,reason:"realtime server not running"};let R=z.private??z.userId!==void 0;return K(J,F,z.data,{private:R}),x.info(`[notifications] broadcast to '${J}' (${F})`),{delivered:!0,channel:J,event:F}}catch(G){let K=G instanceof Error?G.message:String(G);return x.warn(`[notifications] broadcast failed: ${K}`),{delivered:!1,channel:J,event:F,reason:K}}}};import*as M from"@stacksjs/chat";import{log as S}from"@stacksjs/cli";import{db as V}from"@stacksjs/database";var X={async send(z){let F=new Date().toISOString(),G=await V.insertInto("notifications").values({user_id:z.userId,type:z.type,data:JSON.stringify(z.data),read_at:null,created_at:F,updated_at:F}).execute(),K=Array.isArray(G)?G[0]:G,O=Number(K?.insertId??K?.lastInsertRowid??K?.lastInsertId??0);return S.info(`Database notification sent to user ${z.userId}: ${z.type}`),{id:O,user_id:z.userId,type:z.type,data:JSON.stringify(z.data),read_at:null,created_at:F,updated_at:F}},async getUserNotifications(z){return await V.selectFrom("notifications").selectAll().where("user_id","=",z).orderBy("created_at","desc").execute()},async getUnreadNotifications(z){return await V.selectFrom("notifications").selectAll().where("user_id","=",z).where("read_at","is",null).orderBy("created_at","desc").execute()},async markAsRead(z){await V.updateTable("notifications").set({read_at:new Date().toISOString()}).where("id","=",z).execute()},async markAllAsRead(z){await V.updateTable("notifications").set({read_at:new Date().toISOString()}).where("user_id","=",z).where("read_at","is",null).execute()},async unreadCount(z){let F=await V.selectFrom("notifications").select(V.fn.countAll().as("count")).where("user_id","=",z).where("read_at","is",null).executeTakeFirst();return Number(F?.count??0)},async deleteNotification(z){await V.deleteFrom("notifications").where("id","=",z).execute()},async deleteAllNotifications(z){await V.deleteFrom("notifications").where("user_id","=",z).execute()}};import*as A from"@stacksjs/push";import*as L from"@stacksjs/sms";import{log as k}from"@stacksjs/cli";import{db as Y}from"@stacksjs/database";var Z="notification_preferences";function T(z,F){return F===null?z.whereNull("category"):z.where("category","=",F)}async function H(z,F){let J=new Map;try{let G=Y.selectFrom(Z).select(["channel","enabled","category"]).where("user_id","=",z);if(F!==void 0)G=G.where("category","=",F);let K=await G.execute();for(let O of K)J.set(O.channel,O.enabled===!0||O.enabled===1)}catch(G){k.debug?.(`[notifications] preferences lookup failed (table missing?): ${G.message}`)}return J}async function E(z,F,J,G){let K=new Date().toISOString(),O=G??null,R=Y.selectFrom(Z).select(["id"]).where("user_id","=",z).where("channel","=",F),U=await T(R,O).executeTakeFirst();if(U?.id){await Y.updateTable(Z).set({enabled:J,updated_at:K}).where("id","=",U.id).execute();return}await Y.insertInto(Z).values({user_id:z,channel:F,enabled:J,category:O,created_at:K,updated_at:K}).execute()}async function w(z,F){for(let J of F)await E(z,J.channel,J.enabled,J.category)}async function Q(z,F,J){let G=await H(z,J);if(J!==void 0){let K=await H(z,void 0);for(let[O,R]of K)if(!G.has(O))G.set(O,R)}return F.filter((K)=>{let O=G.get(K);return O===void 0?!0:O===!0})}var I=m;function B(z){return M[z||"slack"]}function j(z){if(z)try{return q.use(z)}catch(F){_.warn(`[notifications] email driver '${z}' not registered \u2014 falling back to default mail singleton (${F.message})`)}return q}function N(z){return L[z||"twilio"]}function b(){return A}function g(){return X}function Oz(){return W}function f(z,F){let J=z||I?.default||"email",G=F;switch(J){case"email":return j(G);case"chat":return B(G);case"sms":return N(G);case"database":return g();default:throw Error(`Notification type "${J}" is not supported`)}}function C(z){return!!z&&typeof z==="object"&&"send"in z&&typeof z.send==="function"}async function Rz(z,F,J=["email"],G={}){let K=J;if(z.userId&&!G.ignorePreferences)try{K=await Q(z.userId,J,G.category)}catch(R){_.warn(`[notify] preferences filter failed, sending all channels: ${R.message}`)}return(await Promise.allSettled(K.map(async(R)=>{switch(R){case"email":{if(!z.email)throw Error("[notify] email channel requires recipient.email");await j().send({to:z.email,subject:F.subject??"",text:F.body,html:`<p>${h(F.body)}</p>`});break}case"sms":{if(!z.phone)throw Error("[notify] sms channel requires recipient.phone");let U=N();if(!C(U))throw Error("[notify] sms channel is not configured: no usable SMS driver with a send() method");await U.send({to:z.phone,body:F.body});break}case"chat":{let U=B();if(!C(U))throw Error("[notify] chat channel is not configured: no usable chat driver with a send() method");await U.send({body:F.body});break}case"database":{if(!z.userId)throw Error("[notify] database channel requires recipient.userId");await X.send({userId:z.userId,type:F.subject||"notification",data:{body:F.body,...F.data}});break}case"push":{if(!z.pushTokens||Array.isArray(z.pushTokens)&&z.pushTokens.length===0)throw Error("[notify] push channel requires recipient.pushTokens");await b().send(z.pushTokens,{title:F.subject,body:F.body,data:F.data});break}case"broadcast":{await W.send({channel:z.broadcastChannel,userId:z.userId,event:F.subject??"notification",data:{body:F.body,...F.data}});break}default:throw Error(`Unsupported notification channel: ${R}`)}}))).map((R,U)=>{let $=K[U];if(!$)throw Error(`Missing notification channel for result ${U}`);if(R.status==="rejected"){let D=R.reason instanceof Error?R.reason.message:String(R.reason);_.warn(`[notify] ${$} channel failed: ${D}`)}return{channel:$,success:R.status==="fulfilled",error:R.status==="rejected"?R.reason:void 0}})}function Uz(){return f()}function h(z){return String(z??"").replace(/[&<>"']/g,(F)=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[F])}export{T as wherePreferenceCategory,N as useSMS,b as usePush,f as useNotification,j as useEmail,g as useDatabase,B as useChat,Oz as useBroadcast,E as setNotificationPreference,Rz as notify,Uz as notification,H as getNotificationPreferences,Q as filterChannelsByPreferences,w as bulkSetPreferences,X as DatabaseNotificationDriver,W as BroadcastNotificationDriver};
2
+ var P=import.meta.require;import{log as H}from"@stacksjs/cli";import{notification as u}from"@stacksjs/config";import{mail as E}from"@stacksjs/email";import{log as Q}from"@stacksjs/cli";var G={async send(N){let R=N.event??"notification",O=N.channel;if(!O)O=N.userId!==void 0?`private-user-${N.userId}`:"notifications";try{let _=await import("@stacksjs/realtime").catch(()=>null),$=_?.emit,x=_?.getServer;if(!$||!x)return{delivered:!1,channel:O,event:R,reason:"@stacksjs/realtime is not available"};if(!x())return{delivered:!1,channel:O,event:R,reason:"realtime server not running"};let A=N.private??N.userId!==void 0;return $(O,R,N.data,{private:A}),Q.info(`[notifications] broadcast to '${O}' (${R})`),{delivered:!0,channel:O,event:R}}catch(_){let $=_ instanceof Error?_.message:String(_);return Q.warn(`[notifications] broadcast failed: ${$}`),{delivered:!1,channel:O,event:R,reason:$}}}};import*as T from"@stacksjs/chat";import{log as k}from"@stacksjs/cli";import{db as z}from"@stacksjs/database";var K={async send(N){let R=new Date().toISOString(),_=await z.insertInto("notifications").values({user_id:N.userId,type:N.type,data:JSON.stringify(N.data),read_at:null,created_at:R,updated_at:R}).execute(),$=Array.isArray(_)?_[0]:_,x=Number($?.insertId??$?.lastInsertRowid??$?.lastInsertId??0);return k.info(`Database notification sent to user ${N.userId}: ${N.type}`),{id:x,user_id:N.userId,type:N.type,data:JSON.stringify(N.data),read_at:null,created_at:R,updated_at:R}},async getUserNotifications(N){return await z.selectFrom("notifications").selectAll().where("user_id","=",N).orderBy("created_at","desc").execute()},async getUnreadNotifications(N){return await z.selectFrom("notifications").selectAll().where("user_id","=",N).where("read_at","is",null).orderBy("created_at","desc").execute()},async markAsRead(N){await z.updateTable("notifications").set({read_at:new Date().toISOString()}).where("id","=",N).execute()},async markAllAsRead(N){await z.updateTable("notifications").set({read_at:new Date().toISOString()}).where("user_id","=",N).where("read_at","is",null).execute()},async unreadCount(N){let R=await z.selectFrom("notifications").select(z.fn.countAll().as("count")).where("user_id","=",N).where("read_at","is",null).executeTakeFirst();return Number(R?.count??0)},async deleteNotification(N){await z.deleteFrom("notifications").where("id","=",N).execute()},async deleteAllNotifications(N){await z.deleteFrom("notifications").where("user_id","=",N).execute()}};import*as C from"@stacksjs/push";import*as j from"@stacksjs/sms";import{log as I}from"@stacksjs/cli";import{db as g}from"@stacksjs/database";function M(N,R){switch(R){case"email":return N.email||"";case"sms":return N.phone||"";case"push":return Array.isArray(N.pushTokens)?N.pushTokens.join(", "):N.pushTokens||"";case"broadcast":return N.broadcastChannel||(N.userId?`private-user-${N.userId}`:"notifications");case"database":return N.userId?`User #${N.userId}`:"";case"chat":return"Configured chat destination"}}function X(N,R,O,_,$=new Date().toISOString()){return{userId:N.userId,channel:O.channel,recipient:M(N,O.channel),subject:R.subject,body:R.body,status:O.success?"sent":"failed",error:O.error?.message,metadata:{...R.data,..._.category?{category:_.category}:{}},sentAt:$}}async function Y(N){let R=new Date().toISOString();try{await g.insertInto("notification_deliveries").values({user_id:N.userId??null,channel:N.channel,recipient:N.recipient,subject:N.subject??null,body:N.body,status:N.status,error:N.error??null,metadata:N.metadata?JSON.stringify(N.metadata):null,sent_at:N.sentAt,created_at:R,updated_at:R}).execute()}catch(O){let _=O instanceof Error?O.message:String(O);I.warn(`[notifications] could not record ${N.channel} delivery: ${_}`)}}import{log as b}from"@stacksjs/cli";import{db as V}from"@stacksjs/database";var W="notification_preferences";function L(N,R){return R===null?N.whereNull("category"):N.where("category","=",R)}async function Z(N,R){let O=new Map;try{let _=V.selectFrom(W).select(["channel","enabled","category"]).where("user_id","=",N);if(R!==void 0)_=_.where("category","=",R);let $=await _.execute();for(let x of $)O.set(x.channel,x.enabled===!0||x.enabled===1)}catch(_){b.debug?.(`[notifications] preferences lookup failed (table missing?): ${_.message}`)}return O}async function D(N,R,O,_){let $=new Date().toISOString(),x=_??null,A=V.selectFrom(W).select(["id"]).where("user_id","=",N).where("channel","=",R),J=await L(A,x).executeTakeFirst();if(J?.id){await V.updateTable(W).set({enabled:O,updated_at:$}).where("id","=",J.id).execute();return}await V.insertInto(W).values({user_id:N,channel:R,enabled:O,category:x,created_at:$,updated_at:$}).execute()}async function h(N,R){for(let O of R)await D(N,O.channel,O.enabled,O.category)}async function m(N,R,O){let _=await Z(N,O);if(O!==void 0){let $=await Z(N,void 0);for(let[x,A]of $)if(!_.has(x))_.set(x,A)}return R.filter(($)=>{let x=_.get($);return x===void 0?!0:x===!0})}var y=u;function v(N){if(!N.success)throw Error(N.message||`Email delivery failed through ${N.provider||"the configured provider"}.`)}function f(N){return T[N||"slack"]}function q(N){if(N)try{return E.use(N)}catch(R){H.warn(`[notifications] email driver '${N}' not registered \u2014 falling back to default mail singleton (${R.message})`)}return E}function w(N){return j[N||"twilio"]}function t(){return C}function c(){return K}function YN(){return G}function n(N,R){let O=N||y?.default||"email",_=R;switch(O){case"email":return q(_);case"chat":return f(_);case"sms":return w(_);case"database":return c();default:throw Error(`Notification type "${O}" is not supported`)}}function S(N){return!!N&&typeof N==="object"&&"send"in N&&typeof N.send==="function"}async function ZN(N,R,O=["email"],_={}){let $=O;if(N.userId&&!_.ignorePreferences)try{$=await m(N.userId,O,_.category)}catch(J){H.warn(`[notify] preferences filter failed, sending all channels: ${J.message}`)}let A=(await Promise.allSettled($.map(async(J)=>{switch(J){case"email":{if(!N.email)throw Error("[notify] email channel requires recipient.email");let F=await q().send({to:N.email,subject:R.subject??"",text:R.body,html:`<p>${l(R.body)}</p>`});v(F);break}case"sms":{if(!N.phone)throw Error("[notify] sms channel requires recipient.phone");let U=w();if(!S(U))throw Error("[notify] sms channel is not configured: no usable SMS driver with a send() method");await U.send({to:N.phone,body:R.body});break}case"chat":{let U=f();if(!S(U))throw Error("[notify] chat channel is not configured: no usable chat driver with a send() method");await U.send({body:R.body});break}case"database":{if(!N.userId)throw Error("[notify] database channel requires recipient.userId");await K.send({userId:N.userId,type:R.subject||"notification",data:{body:R.body,...R.data}});break}case"push":{if(!N.pushTokens||Array.isArray(N.pushTokens)&&N.pushTokens.length===0)throw Error("[notify] push channel requires recipient.pushTokens");await t().send(N.pushTokens,{title:R.subject,body:R.body,data:R.data});break}case"broadcast":{await G.send({channel:N.broadcastChannel,userId:N.userId,event:R.subject??"notification",data:{body:R.body,...R.data}});break}default:throw Error(`Unsupported notification channel: ${J}`)}}))).map((J,U)=>{let F=$[U];if(!F)throw Error(`Missing notification channel for result ${U}`);if(J.status==="rejected"){let B=J.reason instanceof Error?J.reason.message:String(J.reason);H.warn(`[notify] ${F} channel failed: ${B}`)}return{channel:F,success:J.status==="fulfilled",error:J.status==="rejected"?J.reason:void 0}});return await Promise.all(A.map((J)=>Y(X(N,R,J,_)))),A}function mN(){return n()}function l(N){return String(N??"").replace(/[&<>"']/g,(R)=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[R])}export{L as wherePreferenceCategory,w as useSMS,t as usePush,n as useNotification,q as useEmail,c as useDatabase,f as useChat,YN as useBroadcast,D as setNotificationPreference,M as resolveDeliveryRecipient,Y as recordNotificationDelivery,ZN as notify,mN as notification,X as makeDeliveryRecord,Z as getNotificationPreferences,m as filterChannelsByPreferences,v as ensureSuccessfulEmailResult,h as bulkSetPreferences,K as DatabaseNotificationDriver,G as BroadcastNotificationDriver};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/notifications",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.70.229",
5
+ "version": "0.70.230",
6
6
  "description": "The Stacks notifications integration.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -59,14 +59,14 @@
59
59
  "prepublishOnly": "bun run build"
60
60
  },
61
61
  "devDependencies": {
62
- "@stacksjs/chat": "0.70.229",
63
- "@stacksjs/cli": "0.70.229",
64
- "@stacksjs/config": "0.70.229",
62
+ "@stacksjs/chat": "0.70.230",
63
+ "@stacksjs/cli": "0.70.230",
64
+ "@stacksjs/config": "0.70.230",
65
65
  "better-dx": "^0.2.17",
66
- "@stacksjs/email": "0.70.229",
67
- "@stacksjs/error-handling": "0.70.229",
68
- "@stacksjs/push": "0.70.229",
69
- "@stacksjs/sms": "0.70.229",
70
- "@stacksjs/types": "0.70.229"
66
+ "@stacksjs/email": "0.70.230",
67
+ "@stacksjs/error-handling": "0.70.230",
68
+ "@stacksjs/push": "0.70.230",
69
+ "@stacksjs/sms": "0.70.230",
70
+ "@stacksjs/types": "0.70.230"
71
71
  }
72
72
  }