@stacksjs/notifications 0.70.256 → 0.70.258

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.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +9 -9
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // @bun
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};
2
+ var I=import.meta.require;import{log as C}from"@stacksjs/cli";import{notification as t}from"@stacksjs/config";import{mail as P}from"@stacksjs/email";import{log as j}from"@stacksjs/cli";var G={async send(N){let R=N.event??"notification",_=N.channel;if(!_)_=N.userId!==void 0?`private-user-${N.userId}`:"notifications";try{let $=await import("@stacksjs/realtime").catch(()=>null),x=$?.emit,O=$?.getServer;if(!x||!O)return{delivered:!1,channel:_,event:R,reason:"@stacksjs/realtime is not available"};if(!O())return{delivered:!1,channel:_,event:R,reason:"realtime server not running"};let A=N.private??N.userId!==void 0;return x(_,R,N.data,{private:A}),j.info(`[notifications] broadcast to '${_}' (${R})`),{delivered:!0,channel:_,event:R}}catch($){let x=$ instanceof Error?$.message:String($);return j.warn(`[notifications] broadcast failed: ${x}`),{delivered:!1,channel:_,event:R,reason:x}}}};import*as M from"@stacksjs/chat";import{log as b}from"@stacksjs/cli";import{db as z,sqlDateTime as X}from"@stacksjs/database";var K={async send(N){let R=X(),$=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(),x=Array.isArray($)?$[0]:$,O=Number(x?.insertId??x?.lastInsertRowid??x?.lastInsertId??0);return b.info(`Database notification sent to user ${N.userId}: ${N.type}`),{id:O,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:X()}).where("id","=",N).execute()},async markAllAsRead(N){await z.updateTable("notifications").set({read_at:X()}).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 m from"@stacksjs/push";import*as L from"@stacksjs/sms";import{log as g}from"@stacksjs/cli";import{db as h,sqlDateTime as T}from"@stacksjs/database";function E(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 Y(N,R,_,$,x=T()){return{userId:N.userId,channel:_.channel,recipient:E(N,_.channel),subject:R.subject,body:R.body,status:_.success?"sent":"failed",error:_.error?.message,metadata:{...R.data,...$.category?{category:$.category}:{}},sentAt:x}}async function Z(N){let R=T();try{await h.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(_){let $=_ instanceof Error?_.message:String(_);g.warn(`[notifications] could not record ${N.channel} delivery: ${$}`)}}import{log as u}from"@stacksjs/cli";import{db as V,sqlDateTime as y}from"@stacksjs/database";var W="notification_preferences";function f(N,R){return R===null?N.whereNull("category"):N.where("category","=",R)}async function H(N,R){let _=new Map;try{let $=V.selectFrom(W).select(["channel","enabled","category"]).where("user_id","=",N);if(R!==void 0)$=$.where("category","=",R);let x=await $.execute();for(let O of x)_.set(O.channel,O.enabled===!0||O.enabled===1)}catch($){u.debug?.(`[notifications] preferences lookup failed (table missing?): ${$.message}`)}return _}async function B(N,R,_,$){let x=y(),O=$??null,A=V.selectFrom(W).select(["id"]).where("user_id","=",N).where("channel","=",R),J=await f(A,O).executeTakeFirst();if(J?.id){await V.updateTable(W).set({enabled:_,updated_at:x}).where("id","=",J.id).execute();return}await V.insertInto(W).values({user_id:N,channel:R,enabled:_,category:O,created_at:x,updated_at:x}).execute()}async function v(N,R){for(let _ of R)await B(N,_.channel,_.enabled,_.category)}async function Q(N,R,_){let $=await H(N,_);if(_!==void 0){let x=await H(N,void 0);for(let[O,A]of x)if(!$.has(O))$.set(O,A)}return R.filter((x)=>{let O=$.get(x);return O===void 0?!0:O===!0})}var c=t;function n(N){if(!N.success)throw Error(N.message||`Email delivery failed through ${N.provider||"the configured provider"}.`)}function w(N){return M[N||"slack"]}function D(N){if(N)try{return P.use(N)}catch(R){C.warn(`[notifications] email driver '${N}' not registered \u2014 falling back to default mail singleton (${R.message})`)}return P}function S(N){return L[N||"twilio"]}function l(){return m}function o(){return K}function QN(){return G}function d(N,R){let _=N||c?.default||"email",$=R;switch(_){case"email":return D($);case"chat":return w($);case"sms":return S($);case"database":return o();default:throw Error(`Notification type "${_}" is not supported`)}}function q(N){return!!N&&typeof N==="object"&&"send"in N&&typeof N.send==="function"}async function CN(N,R,_=["email"],$={}){let x=_;if(N.userId&&!$.ignorePreferences)try{x=await Q(N.userId,_,$.category)}catch(J){C.warn(`[notify] preferences filter failed, sending all channels: ${J.message}`)}let A=(await Promise.allSettled(x.map(async(J)=>{switch(J){case"email":{if(!N.email)throw Error("[notify] email channel requires recipient.email");let F=await D().send({to:N.email,subject:R.subject??"",text:R.body,html:`<p>${p(R.body)}</p>`});n(F);break}case"sms":{if(!N.phone)throw Error("[notify] sms channel requires recipient.phone");let U=S();if(!q(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=w();if(!q(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 l().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=x[U];if(!F)throw Error(`Missing notification channel for result ${U}`);if(J.status==="rejected"){let k=J.reason instanceof Error?J.reason.message:String(J.reason);C.warn(`[notify] ${F} channel failed: ${k}`)}return{channel:F,success:J.status==="fulfilled",error:J.status==="rejected"?J.reason:void 0}});return await Promise.all(A.map((J)=>Z(Y(N,R,J,$)))),A}function jN(){return d()}function p(N){return String(N??"").replace(/[&<>"']/g,(R)=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[R])}export{f as wherePreferenceCategory,S as useSMS,l as usePush,d as useNotification,D as useEmail,o as useDatabase,w as useChat,QN as useBroadcast,B as setNotificationPreference,E as resolveDeliveryRecipient,Z as recordNotificationDelivery,CN as notify,jN as notification,Y as makeDeliveryRecord,H as getNotificationPreferences,Q as filterChannelsByPreferences,n as ensureSuccessfulEmailResult,v 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.256",
5
+ "version": "0.70.258",
6
6
  "description": "The Stacks notifications integration.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -57,14 +57,14 @@
57
57
  "prepublishOnly": "bun run build"
58
58
  },
59
59
  "devDependencies": {
60
- "@stacksjs/chat": "0.70.256",
61
- "@stacksjs/cli": "0.70.256",
62
- "@stacksjs/config": "0.70.256",
60
+ "@stacksjs/chat": "0.70.258",
61
+ "@stacksjs/cli": "0.70.258",
62
+ "@stacksjs/config": "0.70.258",
63
63
  "better-dx": "^0.2.17",
64
- "@stacksjs/email": "0.70.256",
65
- "@stacksjs/error-handling": "0.70.256",
66
- "@stacksjs/push": "0.70.256",
67
- "@stacksjs/sms": "0.70.256",
68
- "@stacksjs/types": "0.70.256"
64
+ "@stacksjs/email": "0.70.258",
65
+ "@stacksjs/error-handling": "0.70.258",
66
+ "@stacksjs/push": "0.70.258",
67
+ "@stacksjs/sms": "0.70.258",
68
+ "@stacksjs/types": "0.70.258"
69
69
  }
70
70
  }