@stacksjs/sms 0.75.575 → 0.75.580

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 CHANGED
@@ -134,3 +134,58 @@ Many thanks to the following core technologies & people who have contributed to
134
134
  The MIT License (MIT). Please see [LICENSE](https://github.com/stacksjs/stacks/tree/main/LICENSE.md) for more information.
135
135
 
136
136
  Made with 💙
137
+
138
+ ### Scoped transport and exact Twilio receipts
139
+
140
+ `TwilioDriver(config, verifyServiceSid?, { fetch?, maxRetries? })` keeps a copy
141
+ of its credentials and accepts an instance-specific transport. A send result
142
+ adds `outcome: 'accepted' | 'rejected' | 'unknown'`. Message-creation retries
143
+ apply only to an explicit HTTP 429 rejection. Timeouts, disconnects, malformed
144
+ acknowledgements and 5xx responses stay unknown, since repeating an accepted
145
+ POST can send the message twice. Reconcile using provider callbacks and
146
+ persisted operations before attempting another send.
147
+
148
+ `getReceipt(messageSid)` returns authoritative status, raw decimal `price`,
149
+ `currency`, segments and `priceMicros`. `twilioPriceMicros` parses a quoted
150
+ absolute decimal price exactly into millionths of the quoted currency, with
151
+ at most six fractional places. For example `-0.007900` becomes `7900`.
152
+ An absent/unparseable price remains undefined, never a fabricated zero.
153
+ The existing numeric `price` field remains available for display. Applications
154
+ must check currency and apply their own billing/markup once to the exact
155
+ provider cost. Provider acceptance is distinct from recipient delivery.
156
+
157
+ ### WhatsApp Cloud text replies
158
+
159
+ `WhatsAppCloudClient({ accessToken, phoneNumberId, apiVersion }, { fetch? })`
160
+ uses a scoped token and explicit Graph API version. `identity()` verifies the
161
+ configured phone-number ID; `sendText(to, text, { replyTo?, callbackData? })`
162
+ sends session text and returns `accepted`, `rejected` or `unknown`, plus a
163
+ provider message ID when acknowledged. It never blindly retries a POST.
164
+ The opaque callback value is for correlating a signed status callback with a
165
+ persisted operation, including a lost HTTP acknowledgement.
166
+
167
+ This low-level client does not grant permission to message a customer. The
168
+ application must enforce consent, opt-outs, provider registration and messaging
169
+ windows. Templates and proactive campaigns require their own explicit flow.
170
+ Phone recipients are international numbers; text is limited to 4,096 characters.
171
+ These clients do not use the local desktop WhatsApp database/inbox driver.
172
+
173
+ Protocol references: [Meta WhatsApp Cloud API](https://www.postman.com/meta/whatsapp-business-platform/documentation/wlk6lh4/whatsapp-cloud-api)
174
+ and [Meta text-message object](https://whatsapp.github.io/WhatsApp-Nodejs-SDK/api-reference/messages/text/).
175
+ The latter SDK is archived; this package implements the HTTP client and does
176
+ not depend on that SDK. Provider protocol fixtures are not live delivery
177
+ qualification.
178
+
179
+ For WhatsApp through Twilio, use channel addresses such as
180
+ `whatsapp:+12065550101`. `getWhatsAppSender(XE...)` reads the registered
181
+ sender and its routing configuration; `getContentApproval(HX...)` reads
182
+ current account-bound template approval. `send` accepts
183
+ `options: { contentSid, contentVariables: { '1': 'value' } }`. Template requests
184
+ omit `Body` and refuse `MediaUrl`, avoiding incompatible content fields.
185
+ Applications must check approval, consent and the 24-hour customer service
186
+ window; these read-only probes never register or purchase a sender.
187
+
188
+ References: [Twilio sender registration](https://www.twilio.com/docs/whatsapp/api/senders),
189
+ [template approvals](https://www.twilio.com/docs/content/content-api-resources),
190
+ [reply windows](https://www.twilio.com/docs/whatsapp/key-concepts), and
191
+ [compatible template fields](https://www.twilio.com/docs/api/errors/63030).
@@ -1,15 +1,45 @@
1
- import type { SmsDriver, SmsMessage, SmsSendResult, SmsStatusUpdate, SmsVerificationDriver, TwilioConfig, VerificationCheckRequest, VerificationRequest, VerificationResult } from '@stacksjs/types';
1
+ import type { SmsDriver, SmsMessage, SmsSendResult, SmsStatus, SmsStatusUpdate, SmsVerificationDriver, TwilioConfig, VerificationCheckRequest, VerificationRequest, VerificationResult } from '@stacksjs/types';
2
+ /** Parse a decimal provider price without floating-point currency rounding. */
3
+ export declare function twilioPriceMicros(value: string | null | undefined): number | undefined;
2
4
  // =============================================================================
3
5
  // Factory Function
4
6
  // =============================================================================
5
- export declare function createTwilioDriver(config: TwilioConfig, verifyServiceSid?: string): TwilioDriver;
7
+ export declare function createTwilioDriver(config: TwilioConfig, verifyServiceSid?: string, transport?: TwilioTransportOptions): TwilioDriver;
8
+ export declare interface TwilioTransportOptions {
9
+ fetch?: typeof fetch
10
+ maxRetries?: number
11
+ }
12
+ export declare interface TwilioSendResult extends SmsSendResult {
13
+ outcome?: 'accepted' | 'rejected' | 'unknown'
14
+ httpStatus?: number
15
+ providerCode?: number
16
+ priceMicros?: number
17
+ }
18
+ export declare interface TwilioReceipt {
19
+ messageId: string
20
+ from?: string
21
+ to?: string
22
+ createdAt?: string
23
+ body?: string
24
+ status: SmsStatus
25
+ price?: string | null
26
+ priceMicros?: number
27
+ currency?: string
28
+ segments?: number
29
+ }
6
30
  export declare class TwilioDriver implements SmsDriver, SmsVerificationDriver {
7
31
  private config;
8
32
  private verifyServiceSid;
9
- constructor(config: TwilioConfig, verifyServiceSid?: string);
10
- send(message: SmsMessage): Promise<SmsSendResult>;
33
+ private fetcher;
34
+ private maxRetries;
35
+ constructor(config: TwilioConfig, verifyServiceSid?: string, transport?: TwilioTransportOptions);
36
+ send(message: SmsMessage): Promise<TwilioSendResult>;
11
37
  sendBulk(messages: SmsMessage[]): Promise<SmsSendResult[]>;
12
38
  getStatus(messageId: string): Promise<SmsStatusUpdate>;
39
+ private readMessagingResource;
40
+ getWhatsAppSender(senderSid: string): Promise<{ sid: string, senderId: string, status: string, callbackUrl?: string }>;
41
+ getContentApproval(contentSid: string): Promise<{ sid: string, status: string, category?: string }>;
42
+ getReceipt(messageId: string): Promise<TwilioReceipt>;
13
43
  verify(phoneNumber: string): Promise<{ valid: boolean, carrier?: string, type?: string }>;
14
44
  getBalance(): Promise<{ balance: number, currency: string }>;
15
45
  startVerification(request: VerificationRequest): Promise<VerificationResult>;
@@ -1 +1 @@
1
- const API_BASE="https://api.twilio.com/2010-04-01";const VERIFY_API_BASE="https://verify.twilio.com/v2";async function fetchWithRetry(url,init,maxRetries=3){let attempt=0;while(true){const response=await fetch(url,init);if(response.status!==429&&response.status!==503)return response;if(attempt>=maxRetries)return response;const retryAfter=Number(response.headers.get("retry-after"))||2**attempt;await new Promise((r)=>setTimeout(r,Math.min(retryAfter,30)*1000));attempt++}}export class TwilioDriver{config;verifyServiceSid;constructor(config,verifyServiceSid){this.config=config;this.verifyServiceSid=verifyServiceSid}async send(message){const recipients=Array.isArray(message.to)?message.to:[message.to];if(recipients.length>1){const results=await this.sendBulk(recipients.map((to)=>({...message,to})));return results[0]??{success:false,to:recipients[0]??"",error:"No recipients supplied",provider:"twilio"}}const to=recipients[0];if(!to){return{success:false,to:"",error:"No recipient supplied",provider:"twilio"}}const from=message.from||this.config.from;if(!from&&!this.config.messagingServiceSid){return{success:false,to,error:'No "from" number or messaging service SID configured',provider:"twilio"}}try{const body=new URLSearchParams;body.append("To",to);body.append("Body",message.body);if(this.config.messagingServiceSid){body.append("MessagingServiceSid",this.config.messagingServiceSid)}else if(from){body.append("From",from)}if(message.statusCallback||this.config.statusCallback){body.append("StatusCallback",message.statusCallback||this.config.statusCallback)}if(message.mediaUrls&&message.mediaUrls.length>0){for(const mediaUrl of message.mediaUrls){body.append("MediaUrl",mediaUrl)}}const response=await fetchWithRetry(`${API_BASE}/Accounts/${this.config.accountSid}/Messages.json`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()});const data=await response.json();if(!response.ok){return{success:false,to,error:data.message||`HTTP ${response.status}`,provider:"twilio"}}return{success:true,messageId:data.sid,status:mapTwilioStatus(data.status),to,provider:"twilio",segments:data.num_segments?Number.parseInt(data.num_segments,10):undefined,price:data.price?Math.abs(Number.parseFloat(data.price)):undefined,currency:data.price_unit}}catch(error){return{success:false,to,error:error instanceof Error?error.message:"Unknown error",provider:"twilio"}}}async sendBulk(messages){return Promise.all(messages.map((msg)=>this.send(msg)))}async getStatus(messageId){const response=await fetch(`${API_BASE}/Accounts/${this.config.accountSid}/Messages/${messageId}.json`,{headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`}});if(!response.ok){throw new Error(`Twilio message status API error: ${response.status}`)}const data=await response.json();return{messageId:data.sid,to:data.to,status:mapTwilioStatus(data.status),timestamp:new Date(data.date_updated||data.date_created),errorCode:data.error_code?.toString(),errorMessage:data.error_message}}async verify(phoneNumber){try{const response=await fetch(`https://lookups.twilio.com/v2/PhoneNumbers/${encodeURIComponent(phoneNumber)}?Fields=line_type_intelligence`,{headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`}});if(!response.ok){return{valid:false}}const data=await response.json();return{valid:data.valid,carrier:data.line_type_intelligence?.carrier_name,type:data.line_type_intelligence?.type}}catch{return{valid:false}}}async getBalance(){const response=await fetch(`${API_BASE}/Accounts/${this.config.accountSid}/Balance.json`,{headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`}});if(!response.ok){throw new Error(`Twilio balance API error: ${response.status}`)}const data=await response.json();return{balance:Number.parseFloat(data.balance),currency:data.currency}}async startVerification(request){if(!this.verifyServiceSid){return{success:false,status:"denied",error:"Verify service SID not configured"}}try{const body=new URLSearchParams;body.append("To",request.to);body.append("Channel",request.channel||"sms");if(request.locale){body.append("Locale",request.locale)}if(request.customMessage){body.append("CustomMessage",request.customMessage)}const response=await fetch(`${VERIFY_API_BASE}/Services/${this.verifyServiceSid}/Verifications`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()});const data=await response.json();if(!response.ok){return{success:false,status:"denied",error:data.message||`HTTP ${response.status}`}}return{success:true,verificationId:data.sid,status:data.status==="pending"?"pending":"denied"}}catch(error){return{success:false,status:"denied",error:error instanceof Error?error.message:"Unknown error"}}}async checkVerification(request){if(!this.verifyServiceSid){return{success:false,status:"denied",error:"Verify service SID not configured"}}try{const body=new URLSearchParams;body.append("To",request.to);body.append("Code",request.code);const response=await fetch(`${VERIFY_API_BASE}/Services/${this.verifyServiceSid}/VerificationCheck`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()});const data=await response.json();if(!response.ok){return{success:false,status:"denied",error:data.message||`HTTP ${response.status}`}}return{success:data.status==="approved",verificationId:data.sid,status:data.status==="approved"?"approved":"denied"}}catch(error){return{success:false,status:"denied",error:error instanceof Error?error.message:"Unknown error"}}}async cancelVerification(verificationId){if(!this.verifyServiceSid){return false}try{const body=new URLSearchParams;body.append("Status","canceled");const response=await fetch(`${VERIFY_API_BASE}/Services/${this.verifyServiceSid}/Verifications/${verificationId}`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()});return response.ok}catch{return false}}}function mapTwilioStatus(status){const statusMap={queued:"queued",sending:"sending",sent:"sent",delivered:"delivered",undelivered:"undelivered",failed:"failed",canceled:"failed"};return statusMap[status]||"unknown"}export function createTwilioDriver(config,verifyServiceSid){return new TwilioDriver(config,verifyServiceSid)}export{TwilioDriver as default};
1
+ const API_BASE="https://api.twilio.com/2010-04-01";const VERIFY_API_BASE="https://verify.twilio.com/v2";export function twilioPriceMicros(value){if(typeof value!=="string"||!/^-?\d+(?:\.\d{1,6})?$/.test(value))return;const[whole,fraction=""]=value.replace(/^-/,"").split(".");const micros=BigInt(whole)*1000000n+BigInt(fraction.padEnd(6,"0"));return micros<=BigInt(Number.MAX_SAFE_INTEGER)?Number(micros):undefined}async function fetchWithRetry(fetcher,url,init,maxRetries=3){let attempt=0;while(true){const response=await fetcher(url,{...init,redirect:"error",signal:init.signal??AbortSignal.timeout(15000)});if(response.status!==429||attempt>=maxRetries)return response;const retryHeader=response.headers.get("retry-after");const seconds=retryHeader===null?2**attempt:Number(retryHeader);await new Promise((r)=>setTimeout(r,Math.max(0,Math.min(Number.isFinite(seconds)?seconds:2**attempt,30))*1000));attempt++}}export class TwilioDriver{config;verifyServiceSid;fetcher;maxRetries;constructor(config,verifyServiceSid,transport={}){this.config={...config};this.fetcher=transport.fetch??((input,init)=>fetch(input,init));this.maxRetries=transport.maxRetries??3;this.verifyServiceSid=verifyServiceSid}async send(message){const recipients=Array.isArray(message.to)?message.to:[message.to];if(recipients.length>1){const results=await this.sendBulk(recipients.map((to)=>({...message,to})));return results[0]??{success:false,to:recipients[0]??"",error:"No recipients supplied",provider:"twilio"}}const to=recipients[0];if(!to){return{success:false,to:"",error:"No recipient supplied",provider:"twilio"}}const from=message.from||this.config.from;if(!from&&!this.config.messagingServiceSid){return{success:false,to,error:'No "from" number or messaging service SID configured',provider:"twilio"}}const contentSid=message.options?.contentSid;const variables=message.options?.contentVariables;if(contentSid!==undefined&&(typeof contentSid!=="string"||!/^HX[a-f0-9]{32}$/i.test(contentSid)))return{success:false,to,provider:"twilio",outcome:"rejected",error:"Invalid Twilio Content SID"};if(contentSid&&message.mediaUrls?.length)return{success:false,to,provider:"twilio",outcome:"rejected",error:"Content templates cannot include MediaUrl"};if(variables!==undefined&&(!contentSid||!variables||typeof variables!=="object"||Array.isArray(variables)||Object.entries(variables).some(([key,value])=>!/^\d+$/.test(key)||typeof value!=="string"||value.length>1600)))return{success:false,to,provider:"twilio",outcome:"rejected",error:"Content variables require a Content SID and numbered string values"};try{const body=new URLSearchParams;body.append("To",to);if(contentSid){body.append("ContentSid",String(contentSid));if(variables)body.append("ContentVariables",JSON.stringify(variables))}else if(message.body){body.append("Body",message.body)}if(this.config.messagingServiceSid){body.append("MessagingServiceSid",this.config.messagingServiceSid)}else if(from){body.append("From",from)}if(message.statusCallback||this.config.statusCallback){body.append("StatusCallback",message.statusCallback||this.config.statusCallback)}if(message.mediaUrls&&message.mediaUrls.length>0){for(const mediaUrl of message.mediaUrls){body.append("MediaUrl",mediaUrl)}}const response=await fetchWithRetry(this.fetcher,`${API_BASE}/Accounts/${this.config.accountSid}/Messages.json`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()},this.maxRetries);const data=await response.json();if(!response.ok){return{success:false,to,error:data.message||`HTTP ${response.status}`,provider:"twilio",outcome:response.status>=500||response.status===408?"unknown":"rejected",httpStatus:response.status,providerCode:data.code}}if(!data.sid)return{success:false,to,provider:"twilio",outcome:"unknown",error:"Twilio acknowledgement has no message SID",httpStatus:response.status};return{success:true,outcome:"accepted",httpStatus:response.status,priceMicros:twilioPriceMicros(data.price),messageId:data.sid,status:mapTwilioStatus(data.status),to,provider:"twilio",segments:data.num_segments?Number.parseInt(data.num_segments,10):undefined,price:data.price?Math.abs(Number.parseFloat(data.price)):undefined,currency:data.price_unit}}catch{return{success:false,to,error:"Twilio acknowledgement unavailable",provider:"twilio",outcome:"unknown"}}}async sendBulk(messages){return Promise.all(messages.map((msg)=>this.send(msg)))}async getStatus(messageId){const response=await this.fetcher(`${API_BASE}/Accounts/${this.config.accountSid}/Messages/${messageId}.json`,{headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`}});if(!response.ok){throw new Error(`Twilio message status API error: ${response.status}`)}const data=await response.json();return{messageId:data.sid,to:data.to,status:mapTwilioStatus(data.status),timestamp:new Date(data.date_updated||data.date_created),errorCode:data.error_code?.toString(),errorMessage:data.error_message}}async readMessagingResource(url){const response=await this.fetcher(url,{headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`},redirect:"error",signal:AbortSignal.timeout(15000)});if(!response.ok)throw new Error(`Twilio messaging resource HTTP ${response.status}`);return await response.json()}async getWhatsAppSender(senderSid){if(!/^XE[a-f0-9]{32}$/i.test(senderSid))throw new Error("Invalid Twilio WhatsApp Sender SID");const data=await this.readMessagingResource(`https://messaging.twilio.com/v2/Channels/Senders/${senderSid}`);if(data.sid!==senderSid||typeof data.sender_id!=="string"||typeof data.status!=="string")throw new Error("Twilio WhatsApp sender acknowledgement mismatch");const webhook=data.webhook&&typeof data.webhook==="object"?data.webhook:{};return{sid:senderSid,senderId:data.sender_id,status:data.status,callbackUrl:typeof webhook.callback_url==="string"?webhook.callback_url:undefined}}async getContentApproval(contentSid){if(!/^HX[a-f0-9]{32}$/i.test(contentSid))throw new Error("Invalid Twilio Content SID");const data=await this.readMessagingResource(`https://content.twilio.com/v1/Content/${contentSid}/ApprovalRequests`);if(data.sid!==contentSid||data.account_sid!==this.config.accountSid)throw new Error("Twilio content approval account mismatch");const whatsapp=data.whatsapp&&typeof data.whatsapp==="object"?data.whatsapp:{};if(typeof whatsapp.status!=="string")throw new Error("Twilio content approval status unavailable");return{sid:contentSid,status:whatsapp.status,category:typeof whatsapp.category==="string"?whatsapp.category:undefined}}async getReceipt(messageId){if(!/^SM[a-f0-9]{32}$/i.test(messageId)&&!/^MM[a-f0-9]{32}$/i.test(messageId))throw new Error("Invalid Twilio message SID");const response=await this.fetcher(`${API_BASE}/Accounts/${this.config.accountSid}/Messages/${messageId}.json`,{headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`},redirect:"error",signal:AbortSignal.timeout(15000)});if(!response.ok)throw new Error(`Twilio receipt API error: ${response.status}`);const data=await response.json();if(data.sid!==messageId)throw new Error("Twilio receipt SID mismatch");return{messageId:data.sid,from:data.from,to:data.to,createdAt:data.date_created,body:data.body,status:mapTwilioStatus(data.status),price:data.price??undefined,priceMicros:twilioPriceMicros(data.price),currency:data.price_unit,segments:data.num_segments?Number.parseInt(data.num_segments,10):undefined}}async verify(phoneNumber){try{const response=await this.fetcher(`https://lookups.twilio.com/v2/PhoneNumbers/${encodeURIComponent(phoneNumber)}?Fields=line_type_intelligence`,{headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`}});if(!response.ok){return{valid:false}}const data=await response.json();return{valid:data.valid,carrier:data.line_type_intelligence?.carrier_name,type:data.line_type_intelligence?.type}}catch{return{valid:false}}}async getBalance(){const response=await this.fetcher(`${API_BASE}/Accounts/${this.config.accountSid}/Balance.json`,{headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`}});if(!response.ok){throw new Error(`Twilio balance API error: ${response.status}`)}const data=await response.json();return{balance:Number.parseFloat(data.balance),currency:data.currency}}async startVerification(request){if(!this.verifyServiceSid){return{success:false,status:"denied",error:"Verify service SID not configured"}}try{const body=new URLSearchParams;body.append("To",request.to);body.append("Channel",request.channel||"sms");if(request.locale){body.append("Locale",request.locale)}if(request.customMessage){body.append("CustomMessage",request.customMessage)}const response=await this.fetcher(`${VERIFY_API_BASE}/Services/${this.verifyServiceSid}/Verifications`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()});const data=await response.json();if(!response.ok){return{success:false,status:"denied",error:data.message||`HTTP ${response.status}`}}return{success:true,verificationId:data.sid,status:data.status==="pending"?"pending":"denied"}}catch(error){return{success:false,status:"denied",error:error instanceof Error?error.message:"Unknown error"}}}async checkVerification(request){if(!this.verifyServiceSid){return{success:false,status:"denied",error:"Verify service SID not configured"}}try{const body=new URLSearchParams;body.append("To",request.to);body.append("Code",request.code);const response=await this.fetcher(`${VERIFY_API_BASE}/Services/${this.verifyServiceSid}/VerificationCheck`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()});const data=await response.json();if(!response.ok){return{success:false,status:"denied",error:data.message||`HTTP ${response.status}`}}return{success:data.status==="approved",verificationId:data.sid,status:data.status==="approved"?"approved":"denied"}}catch(error){return{success:false,status:"denied",error:error instanceof Error?error.message:"Unknown error"}}}async cancelVerification(verificationId){if(!this.verifyServiceSid){return false}try{const body=new URLSearchParams;body.append("Status","canceled");const response=await this.fetcher(`${VERIFY_API_BASE}/Services/${this.verifyServiceSid}/Verifications/${verificationId}`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${this.config.accountSid}:${this.config.authToken}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()});return response.ok}catch{return false}}}function mapTwilioStatus(status){const statusMap={queued:"queued",sending:"sending",sent:"sent",delivered:"delivered",undelivered:"undelivered",failed:"failed",canceled:"failed"};return statusMap[status]||"unknown"}export function createTwilioDriver(config,verifyServiceSid,transport){return new TwilioDriver(config,verifyServiceSid,transport)}export{TwilioDriver as default};
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export type { TwilioReceipt, TwilioSendResult, TwilioTransportOptions } from './drivers/twilio';
2
+ export type { WhatsAppCloudConfig, WhatsAppCloudResult } from './whatsapp-cloud';
1
3
  /**
2
4
  * SMS Package
3
5
  *
@@ -11,6 +13,7 @@ export * from './sms';
11
13
  export { default as SMS } from './sms';
12
14
  // Drivers
13
15
  export * from './drivers/index';
14
- export { TwilioDriver, createTwilioDriver } from './drivers/twilio';
16
+ export { TwilioDriver, createTwilioDriver, twilioPriceMicros } from './drivers/twilio';
15
17
  export { VonageDriver, createVonageDriver } from './drivers/vonage';
16
18
  export * from './compliance';
19
+ export { WhatsAppCloudClient } from './whatsapp-cloud';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export*from"./inbound";export*from"./keywords";export*from"./opt-out";export*from"./sms";export{default as SMS}from"./sms";export*from"./drivers";export{TwilioDriver,createTwilioDriver}from"./drivers/twilio";export{VonageDriver,createVonageDriver}from"./drivers/vonage";export*from"./compliance";
1
+ export*from"./inbound";export*from"./keywords";export*from"./opt-out";export*from"./sms";export{default as SMS}from"./sms";export*from"./drivers";export{TwilioDriver,createTwilioDriver,twilioPriceMicros}from"./drivers/twilio";export{VonageDriver,createVonageDriver}from"./drivers/vonage";export*from"./compliance";export{WhatsAppCloudClient}from"./whatsapp-cloud";
@@ -0,0 +1,20 @@
1
+ export declare interface WhatsAppCloudConfig {
2
+ accessToken: string
3
+ phoneNumberId: string
4
+ apiVersion: string
5
+ }
6
+ export declare interface WhatsAppCloudResult {
7
+ outcome: 'accepted' | 'rejected' | 'unknown'
8
+ messageId?: string
9
+ error?: string
10
+ httpStatus?: number
11
+ }
12
+ /** Per-account Cloud API client. Acceptance is not a delivery receipt. */
13
+ export declare class WhatsAppCloudClient {
14
+ private config;
15
+ private fetcher;
16
+ constructor(config: WhatsAppCloudConfig, transport?: { fetch?: typeof fetch });
17
+ private endpoint;
18
+ identity(): Promise<{ id: string, displayPhoneNumber?: string, verifiedName?: string }>;
19
+ sendText(to: string, text: string, options?: { replyTo?: string, callbackData?: string }): Promise<WhatsAppCloudResult>;
20
+ }
@@ -0,0 +1 @@
1
+ export class WhatsAppCloudClient{config;fetcher;constructor(config,transport={}){if(!/^v\d+\.\d+$/.test(config.apiVersion)||!/^\d+$/.test(config.phoneNumberId)||!config.accessToken)throw new Error("WhatsApp Cloud requires a version, numeric phone number ID and access token");this.config={...config};this.fetcher=transport.fetch??((input,init)=>fetch(input,init))}endpoint(suffix=""){return`https://graph.facebook.com/${this.config.apiVersion}/${this.config.phoneNumberId}${suffix}`}async identity(){const response=await this.fetcher(this.endpoint("?fields=id,display_phone_number,verified_name"),{headers:{Authorization:`Bearer ${this.config.accessToken}`},redirect:"error",signal:AbortSignal.timeout(15000)});if(!response.ok)throw new Error(`WhatsApp identity HTTP ${response.status}`);const data=await response.json();if(data.id!==this.config.phoneNumberId)throw new Error("WhatsApp identity did not match configured phone number ID");return{id:data.id,displayPhoneNumber:data.display_phone_number,verifiedName:data.verified_name}}async sendText(to,text,options={}){if(!/^\+?[1-9]\d{6,14}$/.test(to)||!text||text.length>4096||(options.callbackData?.length??0)>512)return{outcome:"rejected",error:"Valid international recipient and text of 1–4096 characters required"};let response;try{response=await this.fetcher(this.endpoint("/messages"),{method:"POST",redirect:"error",signal:AbortSignal.timeout(15000),headers:{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({messaging_product:"whatsapp",recipient_type:"individual",to:to.replace(/^\+/,""),type:"text",text:{preview_url:false,body:text},...options.replyTo?{context:{message_id:options.replyTo}}:{},...options.callbackData?{biz_opaque_callback_data:options.callbackData}:{}})})}catch{return{outcome:"unknown",error:"WhatsApp acknowledgement unavailable"}}if(!response.ok)return{outcome:response.status>=500||response.status===408?"unknown":"rejected",error:`WhatsApp HTTP ${response.status}`,httpStatus:response.status};try{const data=await response.json();if(data.error)return{outcome:"rejected",error:`WhatsApp error ${data.error.code??"unknown"}`,httpStatus:response.status};const messageId=data.messages?.[0]?.id;return messageId?{outcome:"accepted",messageId,httpStatus:response.status}:{outcome:"unknown",error:"WhatsApp acknowledgement has no message ID",httpStatus:response.status}}catch{return{outcome:"unknown",error:"WhatsApp acknowledgement is not valid JSON",httpStatus:response.status}}}}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/sms",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.575",
5
+ "version": "0.75.580",
6
6
  "description": "The Stacks SMS integration. Painlessly create & manage your inboxes, templates, and send sms.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -63,14 +63,14 @@
63
63
  "prepublishOnly": "bun run build"
64
64
  },
65
65
  "dependencies": {
66
- "@stacksjs/config": "0.75.575",
67
- "@stacksjs/database": "0.75.575"
66
+ "@stacksjs/config": "0.75.580",
67
+ "@stacksjs/database": "0.75.580"
68
68
  },
69
69
  "devDependencies": {
70
- "@stacksjs/cli": "0.75.575",
71
- "@stacksjs/error-handling": "0.75.575",
72
- "@stacksjs/testing": "0.75.575",
73
- "@stacksjs/types": "0.75.575",
70
+ "@stacksjs/cli": "0.75.580",
71
+ "@stacksjs/error-handling": "0.75.580",
72
+ "@stacksjs/testing": "0.75.580",
73
+ "@stacksjs/types": "0.75.580",
74
74
  "better-dx": "^0.2.39"
75
75
  }
76
76
  }