@mesheshq/events 1.0.3 → 1.0.4

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.
@@ -1,4 +1,4 @@
1
- "use strict";var y=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var S=(i,e)=>{for(var t in e)y(i,t,{get:e[t],enumerable:!0})},T=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of E(e))!A.call(i,a)&&a!==t&&y(i,a,{get:()=>e[a],enumerable:!(s=p(e,a))||s.enumerable});return i};var x=i=>T(y({},"__esModule",{value:!0}),i);var U={};S(U,{MeshesApiError:()=>r,MeshesEventsClient:()=>o,default:()=>O});module.exports=x(U);var r=class extends Error{constructor(e,t){super(e),this.name=this.constructor.name,typeof t<"u"&&(this.data=t)}};r.prototype.toJSON=function(i=!1){let e=i===!0?{stack:this.stack}:{};return typeof this.data>"u"?{name:this.name,message:this.message,...e}:{name:this.name,message:this.message,data:this.data,...e}};var w=async i=>{let e=await i.text();if(!e)return null;try{return JSON.parse(e)}catch{return e}};var R=/^mesh_pub_([A-Za-z0-9\-.]+)_([A-Za-z0-9\-.]+)_([^_]+)$/,v=3e4,I=new Set(["x-meshes-publishable-key","x-meshes-client","content-type","accept"]),$=["POST"],k={version:"v1",timeout:5e3,debug:!1},o=class{#r;#a;#i;#u;#h;#s;constructor(e,t={}){if(typeof e!="string"||!{publishableKey:R}.publishableKey.test(e))throw new r(`Missing or invalid publishable key: ${e}`);if(!t||typeof t!="object")throw new r(`Invalid options object: ${typeof t}`,t);if(t={...k,...t},typeof t.version!="string")throw new r(`Invalid API version: ${t.version}`);if(t.version!=="v1")throw new r(`Unsupported API version: ${t.version}`);if(typeof t.timeout<"u"){if(typeof t.timeout!="number")throw new r(`Invalid request timeout: ${t.timeout}`);if(t.timeout<1e3||t.timeout>v)throw new r(`Unsupported request timeout: ${t.timeout}`)}if(typeof t.headers<"u"){if(!t.headers||typeof t.headers!="object"||Array.isArray(t.headers))throw new r(`Invalid additional request headers: ${typeof t.headers}`,t.headers);for(let[a,d]of Object.entries(t.headers)){if(typeof d!="string")throw new r(`Invalid request header value for ${a}: ${typeof d}`,t.headers);if(I.has(a.toLowerCase()))throw new r(`Header not allowed: ${a}`,t.headers)}}this.#a=t,this.#r=e,this.#i=t.apiBaseUrl??`https://api.meshes.io/api/${t.version}`,this.#u={...this.#d(t.headers),"X-Meshes-Client":"Meshes Events Client v1.0.0","Content-Type":"application/json",Accept:"application/json"},this.#h=t.timeout,this.#s=t.debug===!0}#e(){this.#s&&console.debug(...arguments)}#t(){this.#s&&console.error(...arguments)}#l(e){if(this.#r)e.headers["X-Meshes-Publishable-Key"]=this.#r;else throw new r("No Publishable Key Data");return e}#n(e){if(!e||typeof e!="object")throw new r("Invalid event: must be an object",e);if(typeof e.event!="string"||!e.event.trim())throw new r("Invalid event: missing 'event' string",e);if(!e.payload||typeof e.payload!="object")throw new r("Invalid event: missing 'payload' object",e);if(typeof e.payload.email!="string"||!e.payload.email.trim())throw new r("Invalid event: missing payload.email",e)}#d(e){if(!e||typeof e!="object")return{};let t={};for(let[s,a]of Object.entries(e)){if(typeof s!="string"||typeof a!="string"){this.#e("Invalid Header",s,a);continue}let d=s.trim(),l=a.trim();!d||!l||I.has(d.toLowerCase())||(t[d]=l)}return t}#f(e,t){this.#e("Request Options",e,t?"Callback":"Promise");let s=globalThis.AbortController??void 0,a=s?new s:void 0,d=typeof(e==null?void 0:e.timeout)=="number"?e.timeout:this.#h,l=s?setTimeout(()=>a==null?void 0:a.abort(),d):void 0;a===void 0&&this.#e("AbortController","Not Supported; Timeouts won't be enforced");let P=new Promise((n,c)=>{var b;if(typeof e!="object")throw this.#e("Invalid Request Options",e),new r("Invalid request options",e);let m=(b=e==null?void 0:e.method)==null?void 0:b.toUpperCase();if(!m||typeof m!="string")throw this.#e("Invalid Request Method",e),new r("Invalid request method",e);if(!$.includes(m))throw this.#e("Invalid Request Method Option",e),new r("Unsupported request method",e);if(!(e!=null&&e.path)||typeof e.path!="string"||e.path.trim().length===0||e.path.trim()==="/")throw this.#e("Invalid Request Path",e),new r("Invalid request path",e);if(typeof(e==null?void 0:e.timeout)<"u"){if(typeof e.timeout!="number")throw this.#e("Invalid Request Timeout",e),new r("Invalid request timeout",e);if(e.timeout<1e3||e.timeout>v)throw this.#e("Unsupported Request Timeout",e),new r("Unsupported request timeout",e)}if(typeof e.query<"u"&&(!e.query||typeof e.query!="object"||Array.isArray(e.query)))throw this.#e("Invalid Request Query Params",e),new r("Invalid request query params",e);try{let f=e.query?`?${new URLSearchParams(e.query).toString()}`:"",g=this.#l({method:m,headers:{...this.#d(e.headers),...this.#u},body:e.body?typeof e.body=="string"?e.body:JSON.stringify(e.body):null,signal:a==null?void 0:a.signal}),q=e.path.charAt(0)!=="/"?`/${e.path}`:e.path;return this.#e("Fetch Options",{method:g.method,path:q,query:f}),fetch(`${this.#i}${q}${f}`,g).then(u=>{u.ok?w(u).then(h=>{this.#e("Response Success"),n(h)}).catch(h=>{this.#t("Response Parsing Error",h),c(new r("Error parsing response data",h))}):w(u).then(h=>{this.#e("Response Error",h),c(new r("Meshes API request failed",{status:u.status,statusText:u.statusText,data:h}))}).catch(h=>{this.#t("Response Parsing Failure",h),c(new r("Error parsing request failure",{status:u.status,statusText:u.statusText,error:h}))})}).catch(u=>{this.#t("Request Failure",u),c(new r("Request Failure",u))})}catch(f){throw this.#t("Unexpected Error",f),c(new r("Unexpected Error",f)),f}}).then(n=>{if(this.#e("Promise Success",n),t){this.#e("Promise Success","Callback Success"),t(null,n);return}return n}).catch(n=>{if(this.#e("Promise Error",n),t){this.#e("Promise Error","Callback Error"),t(n);return}throw n}).finally(()=>{l&&clearTimeout(l)});if(!t)return this.#e("Promise Returned","No callback"),P}emit(e,t={},s=void 0){return this.#n(e),this.#f({...this.#a,...t,path:"/events",method:"POST",body:e},s)}emitBatch(e,t={},s=void 0){if(!Array.isArray(e))throw new r("Events must be an array",e);if(e.length===0)throw new r("Events array cannot be empty");if(e.length>100)throw new r("Bulk emit supports up to 100 events per request",{count:e.length});for(let a of e)this.#n(a);return this.#f({...this.#a,...t,path:"/events/bulk",method:"POST",body:e},s)}},O=o;0&&(module.exports={MeshesApiError,MeshesEventsClient});
1
+ "use strict";var o=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var S=(i,e)=>{for(var t in e)o(i,t,{get:e[t],enumerable:!0})},T=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of x(e))!A.call(i,a)&&a!==t&&o(i,a,{get:()=>e[a],enumerable:!(s=E(e,a))||s.enumerable});return i};var R=i=>T(o({},"__esModule",{value:!0}),i);var U={};S(U,{MeshesApiError:()=>r,MeshesEventsClient:()=>b,default:()=>M});module.exports=R(U);var r=class extends Error{constructor(e,t){super(e),this.name=this.constructor.name,typeof t<"u"&&(this.data=t)}};r.prototype.toJSON=function(i=!1){let e=i===!0?{stack:this.stack}:{};return typeof this.data>"u"?{name:this.name,message:this.message,...e}:{name:this.name,message:this.message,data:this.data,...e}};var y=async i=>{let e=await i.text();if(!e)return null;try{return JSON.parse(e)}catch{return e}};var $=/^mesh_pub_([A-Za-z0-9\-.]+)_([A-Za-z0-9\-.]+)_([^_]+)$/,p=3e4,I=new Set(["x-meshes-publishable-key","x-meshes-client","content-type","accept"]),k=["POST"],O={version:"v1",timeout:5e3,debug:!1},w=class{#r;#a;#i;#u;#h;#s;constructor(e,t={}){if(typeof e!="string"||!{publishableKey:$}.publishableKey.test(e))throw new r(`Missing or invalid publishable key: ${e}`);if(!t||typeof t!="object")throw new r(`Invalid options object: ${typeof t}`,t);if(t={...O,...t},typeof t.version!="string")throw new r(`Invalid API version: ${t.version}`);if(t.version!=="v1")throw new r(`Unsupported API version: ${t.version}`);if(typeof t.timeout<"u"){if(typeof t.timeout!="number")throw new r(`Invalid request timeout: ${t.timeout}`);if(t.timeout<1e3||t.timeout>p)throw new r(`Unsupported request timeout: ${t.timeout}`)}if(typeof t.headers<"u"){if(!t.headers||typeof t.headers!="object"||Array.isArray(t.headers))throw new r(`Invalid additional request headers: ${typeof t.headers}`,t.headers);for(let[a,d]of Object.entries(t.headers)){if(typeof d!="string")throw new r(`Invalid request header value for ${a}: ${typeof d}`,t.headers);if(I.has(a.toLowerCase()))throw new r(`Header not allowed: ${a}`,t.headers)}}this.#a=t,this.#r=e,this.#i=t.apiBaseUrl??`https://api.meshes.io/api/${t.version}`,this.#u={...this.#d(t.headers),"X-Meshes-Client":"Meshes Events Client v1.0.0","Content-Type":"application/json",Accept:"application/json"},this.#h=t.timeout,this.#s=t.debug===!0}#e(e){this.#s&&console.debug(...arguments)}#t(e){this.#s&&console.error(...arguments)}#l(e){if(this.#r)e.headers["X-Meshes-Publishable-Key"]=this.#r;else throw new r("No Publishable Key Data");return e}#n(e){if(!e||typeof e!="object")throw new r("Invalid event: must be an object",e);if(typeof e.event!="string"||!e.event.trim())throw new r("Invalid event: missing 'event' string",e);if(!e.payload||typeof e.payload!="object")throw new r("Invalid event: missing 'payload' object",e);if(typeof e.payload.email!="string"||!e.payload.email.trim())throw new r("Invalid event: missing payload.email",e)}#d(e){if(!e||typeof e!="object")return{};let t={};for(let[s,a]of Object.entries(e)){if(typeof s!="string"||typeof a!="string"){this.#e("Invalid Header",s,a);continue}let d=s.trim(),l=a.trim();!d||!l||I.has(d.toLowerCase())||(t[d]=l)}return t}#f(e,t){this.#e("Request Options",e,t?"Callback":"Promise");let s=globalThis.AbortController??void 0,a=s?new s:void 0,d=typeof(e==null?void 0:e.timeout)=="number"?e.timeout:this.#h,l=s?setTimeout(()=>a==null?void 0:a.abort(),d):void 0;a===void 0&&this.#e("AbortController","Not Supported; Timeouts won't be enforced");let P=new Promise((n,c)=>{var g;if(typeof e!="object")throw this.#e("Invalid Request Options",e),new r("Invalid request options",e);let m=(g=e==null?void 0:e.method)==null?void 0:g.toUpperCase();if(!m||typeof m!="string")throw this.#e("Invalid Request Method",e),new r("Invalid request method",e);if(!k.includes(m))throw this.#e("Invalid Request Method Option",e),new r("Unsupported request method",e);if(!(e!=null&&e.path)||typeof e.path!="string"||e.path.trim().length===0||e.path.trim()==="/")throw this.#e("Invalid Request Path",e),new r("Invalid request path",e);if(typeof(e==null?void 0:e.timeout)<"u"){if(typeof e.timeout!="number")throw this.#e("Invalid Request Timeout",e),new r("Invalid request timeout",e);if(e.timeout<1e3||e.timeout>p)throw this.#e("Unsupported Request Timeout",e),new r("Unsupported request timeout",e)}if(typeof e.query<"u"&&(!e.query||typeof e.query!="object"||Array.isArray(e.query)))throw this.#e("Invalid Request Query Params",e),new r("Invalid request query params",e);try{let f=e.query?`?${new URLSearchParams(e.query).toString()}`:"",v=this.#l({method:m,headers:{...this.#d(e.headers),...this.#u},body:e.body?typeof e.body=="string"?e.body:JSON.stringify(e.body):null,signal:a==null?void 0:a.signal}),q=e.path.charAt(0)!=="/"?`/${e.path}`:e.path;return this.#e("Fetch Options",{method:v.method,path:q,query:f}),fetch(`${this.#i}${q}${f}`,v).then(u=>{u.ok?y(u).then(h=>{this.#e("Response Success"),n(h)}).catch(h=>{this.#t("Response Parsing Error",h),c(new r("Error parsing response data",h))}):y(u).then(h=>{this.#e("Response Error",h),c(new r("Meshes API request failed",{status:u.status,statusText:u.statusText,data:h}))}).catch(h=>{this.#t("Response Parsing Failure",h),c(new r("Error parsing request failure",{status:u.status,statusText:u.statusText,error:h}))})}).catch(u=>{this.#t("Request Failure",u),c(new r("Request Failure",u))})}catch(f){throw this.#t("Unexpected Error",f),c(new r("Unexpected Error",f)),f}}).then(n=>{if(this.#e("Promise Success",n),t){this.#e("Promise Success","Callback Success"),t(null,n);return}return n}).catch(n=>{if(this.#e("Promise Error",n),t){this.#e("Promise Error","Callback Error"),t(n);return}throw n}).finally(()=>{l&&clearTimeout(l)});if(!t)return this.#e("Promise Returned","No callback"),P}emit(e,t={},s=void 0){return this.#n(e),this.#f({...this.#a,...t,path:"/events",method:"POST",body:e},s)}emitBatch(e,t={},s=void 0){if(!Array.isArray(e))throw new r("Events must be an array",e);if(e.length===0)throw new r("Events array cannot be empty");if(e.length>100)throw new r("Bulk emit supports up to 100 events per request",{count:e.length});for(let a of e)this.#n(a);return this.#f({...this.#a,...t,path:"/events/bulk",method:"POST",body:e},s)}},b=w;var M=b;0&&(module.exports={MeshesApiError,MeshesEventsClient});
2
2
  /**
3
3
  * JavaScript Meshes Events Client
4
4
  * @module meshes-events-client
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Meshes API Client
3
+ * @class
4
+ */
5
+ export class MeshesEventsClient {
6
+ /**
7
+ * Create the Meshes API Client.
8
+ * @param {string} publishableKey - Meshes publishable key
9
+ * @param {MeshesOptions} options - Additional options
10
+ * @constructor - Meshes API constructor
11
+ */
12
+ constructor(publishableKey: string, options?: MeshesOptions);
13
+ /**
14
+ * Create (emit) a single event
15
+ * @param {MeshesEventBody} event - The event to emit
16
+ * @param {MeshesOptionalRequestOptions} event - Request options
17
+ * @param {CallbackFunctionSingle | undefined} done - Callback function
18
+ * @returns {Promise<CreateEventResponseSingle> | undefined} - Request promise or undefined if a callback is provided
19
+ * @throws {MeshesApiError} - Invalid request
20
+ */
21
+ emit(event: MeshesEventBody, options?: {}, done?: CallbackFunctionSingle | undefined): Promise<CreateEventResponseSingle> | undefined;
22
+ /**
23
+ * Create (emit) multiple events up to 100 at a time
24
+ * @param {MeshesEventBody[]} events - The events to emit
25
+ * @param {MeshesOptionalRequestOptions} options - Request options
26
+ * @param {CallbackFunctionBulk | undefined} done - Callback function
27
+ * @returns {Promise<BulkCreateEventsResult> | undefined} - Request promise or undefined if a callback is provided
28
+ * @throws {MeshesApiError} - Invalid request
29
+ */
30
+ emitBatch(events: MeshesEventBody[], options?: MeshesOptionalRequestOptions, done?: CallbackFunctionBulk | undefined): Promise<BulkCreateEventsResult> | undefined;
31
+ #private;
32
+ }
33
+ export default MeshesEventsClient;
34
+ export { MeshesApiError };
35
+ export type Headers = import("./index.js").Headers;
36
+ export type MeshesOptions = import("./index.js").MeshesOptions;
37
+ export type MeshesRequestOptions = import("./index.js").MeshesRequestOptions;
38
+ export type MeshesOptionalRequestOptions = import("./index.js").MeshesOptionalRequestOptions;
39
+ export type MeshesEventBody = import("./index.js").MeshesEventBody;
40
+ export type CreateEventResponseSingle = import("./index.js").CreateEventResponseSingle;
41
+ export type BulkCreateEventsResult = import("./index.js").BulkCreateEventsResult;
42
+ export type CallbackFunctionSingle = import("./index.js").CallbackFunction<CreateEventResponseSingle>;
43
+ export type CallbackFunctionBulk = import("./index.js").CallbackFunction<BulkCreateEventsResult>;
44
+ export type CallbackAny = import("./index.js").CallbackFunction<any>;
45
+ export type MeshesRequestInit = {
46
+ method: string;
47
+ headers: Headers;
48
+ body: string | null;
49
+ signal?: AbortSignal;
50
+ };
51
+ import { MeshesApiError } from "./lib/errors.js";
package/dist/index.d.ts CHANGED
@@ -1,140 +1,4 @@
1
- /**
2
- * Typescript type definitions for Meshes Events API
3
- * @module meshes-events-client
4
- * @license MIT
5
- * @since 1.0.0
6
- * @description Meshes events client for emitting events with a publishable key.
7
- * @repository https://github.com/mesheshq/node-meshes-events-client
8
- */
9
- /**
10
- * Callback function to use rather than promises
11
- */
12
- export type CallbackFunction = (err: any, data?: any) => void;
13
- /**
14
- * Request headers
15
- */
16
- export type Headers = {
17
- [key: string]: string;
18
- };
19
- /**
20
- * Query parameters
21
- */
22
- export type QueryParams = {
23
- [key: string]: string | number | boolean;
24
- };
25
- /**
26
- * Meshes API Config Options
27
- */
28
- export type MeshesOptions = {
29
- /**
30
- * API version
31
- */
32
- version: "v1";
33
- /**
34
- * Request timeout in milliseconds
35
- * @constraint [1000-30000]
36
- */
37
- timeout: number;
38
- /**
39
- * Additional request headers
40
- */
41
- headers: Headers;
42
- /**
43
- * If true, will enable debug mode.
44
- */
45
- debug?: boolean;
46
- /**
47
- * API Base Url. This is optional and can be useful for testing.
48
- * @default "https://api.meshes.io/api/v1"
49
- */
50
- apiBaseUrl?: string;
51
- };
52
- /**
53
- * Meshes API Optional Request Options
54
- */
55
- export type MeshesOptionalRequestOptions = {
56
- /**
57
- * Request headers
58
- */
59
- headers?: Headers;
60
- /**
61
- * Query parameters
62
- */
63
- query?: QueryParams;
64
- /**
65
- * Request timeout in milliseconds
66
- */
67
- timeout?: number;
68
- };
69
- /**
70
- * Meshes event payload structure.
71
- */
72
- export type MeshesEventPayload = {
73
- /**
74
- * The payload email. This is required.
75
- */
76
- email: string;
77
- first_name?: string | undefined;
78
- id?: string | undefined;
79
- ip_address?: string | undefined;
80
- last_name?: string | undefined;
81
- name?: string | undefined;
82
- phone?: string | undefined;
83
- resource_url?: string | undefined;
84
- } & {
85
- [k: string]: unknown;
86
- };
87
- /**
88
- * Meshes event structure.
89
- */
90
- export type MeshesEventBody = {
91
- /**
92
- * The event type for the event.
93
- */
94
- event: string;
95
- /**
96
- * The custom resource. Defaults to 'global'.
97
- */
98
- resource?: string | undefined;
99
- /**
100
- * The resource ID for a custom resource.
101
- */
102
- resource_id?: string | undefined;
103
- /**
104
- * The event payload that will be used.
105
- */
106
- payload: MeshesEventPayload;
107
- };
108
- /**
109
- * Meshes Events API Client
110
- * @class
111
- * @property {Function} emit - Create (emit) a single event
112
- * @property {Function} emitBatch - Create (emit) multiple events up to 100 at a time
113
- */
114
- export type MeshesEventsClient = {
115
- /**
116
- * Create (emit) a single event
117
- * @param {MeshesEventBody} event - The event to emit
118
- * @param {MeshesOptionalRequestOptions} options - Optional request options
119
- * @param {CallbackFunction} done - Optional callback function
120
- * @returns {Promise<any> | undefined} - Request promise or undefined if a callback is provided
121
- */
122
- emit(event: MeshesEventBody, options?: MeshesOptionalRequestOptions, done?: CallbackFunction): Promise<any> | undefined;
123
- /**
124
- * Create (emit) multiple events up to 100 at a time
125
- * @param {MeshesEventBody[]} events - The events to emit
126
- * @param {MeshesOptionalRequestOptions} options - Optional request options
127
- * @param {CallbackFunction} done - Optional callback function
128
- * @returns {Promise<any> | undefined} - Request promise or undefined if a callback is provided
129
- */
130
- emitBatch(events: MeshesEventBody[], options?: MeshesOptionalRequestOptions, done?: CallbackFunction): Promise<any> | undefined;
131
- };
132
- /**
133
- * Meshes API Error
134
- */
135
- export type MeshesApiError = {
136
- name: string;
137
- message: string;
138
- data?: any;
139
- stack?: any;
140
- };
1
+ export default MeshesEventsClient;
2
+ import MeshesEventsClient from "./client.js";
3
+ import { MeshesApiError } from "./client.js";
4
+ export { MeshesEventsClient, MeshesApiError };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Meshes Event API Error
3
+ * @extends {Error} - Error class
4
+ * @param {string} message - Error message
5
+ * @param {unknown} data - Additional error data
6
+ * @type {import("../index.js").MeshesApiError} - Meshes API Error
7
+ */
8
+ export class MeshesApiError extends Error {
9
+ /**
10
+ * @param {string | undefined} message
11
+ * @param {unknown} [data]
12
+ */
13
+ constructor(message: string | undefined, data?: unknown);
14
+ data: any;
15
+ /**
16
+ * Convert error to JSON
17
+ * @param {boolean} stack - Include stack trace
18
+ * @returns {Record<string,any>} - JSON object with error properties
19
+ */
20
+ toJSON(stack?: boolean): Record<string, any>;
21
+ }
@@ -0,0 +1 @@
1
+ export function readBody(response: any): Promise<unknown | string | null>;
package/dist/mjs/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var r=class extends Error{constructor(e,t){super(e),this.name=this.constructor.name,typeof t<"u"&&(this.data=t)}};r.prototype.toJSON=function(f=!1){let e=f===!0?{stack:this.stack}:{};return typeof this.data>"u"?{name:this.name,message:this.message,...e}:{name:this.name,message:this.message,data:this.data,...e}};var o=async f=>{let e=await f.text();if(!e)return null;try{return JSON.parse(e)}catch{return e}};var P=/^mesh_pub_([A-Za-z0-9\-.]+)_([A-Za-z0-9\-.]+)_([^_]+)$/,q=3e4,v=new Set(["x-meshes-publishable-key","x-meshes-client","content-type","accept"]),p=["POST"],E={version:"v1",timeout:5e3,debug:!1},y=class{#r;#a;#i;#u;#h;#s;constructor(e,t={}){if(typeof e!="string"||!{publishableKey:P}.publishableKey.test(e))throw new r(`Missing or invalid publishable key: ${e}`);if(!t||typeof t!="object")throw new r(`Invalid options object: ${typeof t}`,t);if(t={...E,...t},typeof t.version!="string")throw new r(`Invalid API version: ${t.version}`);if(t.version!=="v1")throw new r(`Unsupported API version: ${t.version}`);if(typeof t.timeout<"u"){if(typeof t.timeout!="number")throw new r(`Invalid request timeout: ${t.timeout}`);if(t.timeout<1e3||t.timeout>q)throw new r(`Unsupported request timeout: ${t.timeout}`)}if(typeof t.headers<"u"){if(!t.headers||typeof t.headers!="object"||Array.isArray(t.headers))throw new r(`Invalid additional request headers: ${typeof t.headers}`,t.headers);for(let[a,n]of Object.entries(t.headers)){if(typeof n!="string")throw new r(`Invalid request header value for ${a}: ${typeof n}`,t.headers);if(v.has(a.toLowerCase()))throw new r(`Header not allowed: ${a}`,t.headers)}}this.#a=t,this.#r=e,this.#i=t.apiBaseUrl??`https://api.meshes.io/api/${t.version}`,this.#u={...this.#d(t.headers),"X-Meshes-Client":"Meshes Events Client v1.0.0","Content-Type":"application/json",Accept:"application/json"},this.#h=t.timeout,this.#s=t.debug===!0}#e(){this.#s&&console.debug(...arguments)}#t(){this.#s&&console.error(...arguments)}#l(e){if(this.#r)e.headers["X-Meshes-Publishable-Key"]=this.#r;else throw new r("No Publishable Key Data");return e}#n(e){if(!e||typeof e!="object")throw new r("Invalid event: must be an object",e);if(typeof e.event!="string"||!e.event.trim())throw new r("Invalid event: missing 'event' string",e);if(!e.payload||typeof e.payload!="object")throw new r("Invalid event: missing 'payload' object",e);if(typeof e.payload.email!="string"||!e.payload.email.trim())throw new r("Invalid event: missing payload.email",e)}#d(e){if(!e||typeof e!="object")return{};let t={};for(let[s,a]of Object.entries(e)){if(typeof s!="string"||typeof a!="string"){this.#e("Invalid Header",s,a);continue}let n=s.trim(),l=a.trim();!n||!l||v.has(n.toLowerCase())||(t[n]=l)}return t}#f(e,t){this.#e("Request Options",e,t?"Callback":"Promise");let s=globalThis.AbortController??void 0,a=s?new s:void 0,n=typeof(e==null?void 0:e.timeout)=="number"?e.timeout:this.#h,l=s?setTimeout(()=>a==null?void 0:a.abort(),n):void 0;a===void 0&&this.#e("AbortController","Not Supported; Timeouts won't be enforced");let I=new Promise((h,c)=>{var w;if(typeof e!="object")throw this.#e("Invalid Request Options",e),new r("Invalid request options",e);let m=(w=e==null?void 0:e.method)==null?void 0:w.toUpperCase();if(!m||typeof m!="string")throw this.#e("Invalid Request Method",e),new r("Invalid request method",e);if(!p.includes(m))throw this.#e("Invalid Request Method Option",e),new r("Unsupported request method",e);if(!(e!=null&&e.path)||typeof e.path!="string"||e.path.trim().length===0||e.path.trim()==="/")throw this.#e("Invalid Request Path",e),new r("Invalid request path",e);if(typeof(e==null?void 0:e.timeout)<"u"){if(typeof e.timeout!="number")throw this.#e("Invalid Request Timeout",e),new r("Invalid request timeout",e);if(e.timeout<1e3||e.timeout>q)throw this.#e("Unsupported Request Timeout",e),new r("Unsupported request timeout",e)}if(typeof e.query<"u"&&(!e.query||typeof e.query!="object"||Array.isArray(e.query)))throw this.#e("Invalid Request Query Params",e),new r("Invalid request query params",e);try{let d=e.query?`?${new URLSearchParams(e.query).toString()}`:"",b=this.#l({method:m,headers:{...this.#d(e.headers),...this.#u},body:e.body?typeof e.body=="string"?e.body:JSON.stringify(e.body):null,signal:a==null?void 0:a.signal}),g=e.path.charAt(0)!=="/"?`/${e.path}`:e.path;return this.#e("Fetch Options",{method:b.method,path:g,query:d}),fetch(`${this.#i}${g}${d}`,b).then(i=>{i.ok?o(i).then(u=>{this.#e("Response Success"),h(u)}).catch(u=>{this.#t("Response Parsing Error",u),c(new r("Error parsing response data",u))}):o(i).then(u=>{this.#e("Response Error",u),c(new r("Meshes API request failed",{status:i.status,statusText:i.statusText,data:u}))}).catch(u=>{this.#t("Response Parsing Failure",u),c(new r("Error parsing request failure",{status:i.status,statusText:i.statusText,error:u}))})}).catch(i=>{this.#t("Request Failure",i),c(new r("Request Failure",i))})}catch(d){throw this.#t("Unexpected Error",d),c(new r("Unexpected Error",d)),d}}).then(h=>{if(this.#e("Promise Success",h),t){this.#e("Promise Success","Callback Success"),t(null,h);return}return h}).catch(h=>{if(this.#e("Promise Error",h),t){this.#e("Promise Error","Callback Error"),t(h);return}throw h}).finally(()=>{l&&clearTimeout(l)});if(!t)return this.#e("Promise Returned","No callback"),I}emit(e,t={},s=void 0){return this.#n(e),this.#f({...this.#a,...t,path:"/events",method:"POST",body:e},s)}emitBatch(e,t={},s=void 0){if(!Array.isArray(e))throw new r("Events must be an array",e);if(e.length===0)throw new r("Events array cannot be empty");if(e.length>100)throw new r("Bulk emit supports up to 100 events per request",{count:e.length});for(let a of e)this.#n(a);return this.#f({...this.#a,...t,path:"/events/bulk",method:"POST",body:e},s)}},R=y;export{r as MeshesApiError,y as MeshesEventsClient,R as default};
1
+ var r=class extends Error{constructor(e,t){super(e),this.name=this.constructor.name,typeof t<"u"&&(this.data=t)}};r.prototype.toJSON=function(f=!1){let e=f===!0?{stack:this.stack}:{};return typeof this.data>"u"?{name:this.name,message:this.message,...e}:{name:this.name,message:this.message,data:this.data,...e}};var o=async f=>{let e=await f.text();if(!e)return null;try{return JSON.parse(e)}catch{return e}};var P=/^mesh_pub_([A-Za-z0-9\-.]+)_([A-Za-z0-9\-.]+)_([^_]+)$/,v=3e4,q=new Set(["x-meshes-publishable-key","x-meshes-client","content-type","accept"]),E=["POST"],x={version:"v1",timeout:5e3,debug:!1},y=class{#r;#a;#i;#u;#h;#s;constructor(e,t={}){if(typeof e!="string"||!{publishableKey:P}.publishableKey.test(e))throw new r(`Missing or invalid publishable key: ${e}`);if(!t||typeof t!="object")throw new r(`Invalid options object: ${typeof t}`,t);if(t={...x,...t},typeof t.version!="string")throw new r(`Invalid API version: ${t.version}`);if(t.version!=="v1")throw new r(`Unsupported API version: ${t.version}`);if(typeof t.timeout<"u"){if(typeof t.timeout!="number")throw new r(`Invalid request timeout: ${t.timeout}`);if(t.timeout<1e3||t.timeout>v)throw new r(`Unsupported request timeout: ${t.timeout}`)}if(typeof t.headers<"u"){if(!t.headers||typeof t.headers!="object"||Array.isArray(t.headers))throw new r(`Invalid additional request headers: ${typeof t.headers}`,t.headers);for(let[a,n]of Object.entries(t.headers)){if(typeof n!="string")throw new r(`Invalid request header value for ${a}: ${typeof n}`,t.headers);if(q.has(a.toLowerCase()))throw new r(`Header not allowed: ${a}`,t.headers)}}this.#a=t,this.#r=e,this.#i=t.apiBaseUrl??`https://api.meshes.io/api/${t.version}`,this.#u={...this.#d(t.headers),"X-Meshes-Client":"Meshes Events Client v1.0.0","Content-Type":"application/json",Accept:"application/json"},this.#h=t.timeout,this.#s=t.debug===!0}#e(e){this.#s&&console.debug(...arguments)}#t(e){this.#s&&console.error(...arguments)}#l(e){if(this.#r)e.headers["X-Meshes-Publishable-Key"]=this.#r;else throw new r("No Publishable Key Data");return e}#n(e){if(!e||typeof e!="object")throw new r("Invalid event: must be an object",e);if(typeof e.event!="string"||!e.event.trim())throw new r("Invalid event: missing 'event' string",e);if(!e.payload||typeof e.payload!="object")throw new r("Invalid event: missing 'payload' object",e);if(typeof e.payload.email!="string"||!e.payload.email.trim())throw new r("Invalid event: missing payload.email",e)}#d(e){if(!e||typeof e!="object")return{};let t={};for(let[s,a]of Object.entries(e)){if(typeof s!="string"||typeof a!="string"){this.#e("Invalid Header",s,a);continue}let n=s.trim(),l=a.trim();!n||!l||q.has(n.toLowerCase())||(t[n]=l)}return t}#f(e,t){this.#e("Request Options",e,t?"Callback":"Promise");let s=globalThis.AbortController??void 0,a=s?new s:void 0,n=typeof(e==null?void 0:e.timeout)=="number"?e.timeout:this.#h,l=s?setTimeout(()=>a==null?void 0:a.abort(),n):void 0;a===void 0&&this.#e("AbortController","Not Supported; Timeouts won't be enforced");let I=new Promise((h,c)=>{var w;if(typeof e!="object")throw this.#e("Invalid Request Options",e),new r("Invalid request options",e);let m=(w=e==null?void 0:e.method)==null?void 0:w.toUpperCase();if(!m||typeof m!="string")throw this.#e("Invalid Request Method",e),new r("Invalid request method",e);if(!E.includes(m))throw this.#e("Invalid Request Method Option",e),new r("Unsupported request method",e);if(!(e!=null&&e.path)||typeof e.path!="string"||e.path.trim().length===0||e.path.trim()==="/")throw this.#e("Invalid Request Path",e),new r("Invalid request path",e);if(typeof(e==null?void 0:e.timeout)<"u"){if(typeof e.timeout!="number")throw this.#e("Invalid Request Timeout",e),new r("Invalid request timeout",e);if(e.timeout<1e3||e.timeout>v)throw this.#e("Unsupported Request Timeout",e),new r("Unsupported request timeout",e)}if(typeof e.query<"u"&&(!e.query||typeof e.query!="object"||Array.isArray(e.query)))throw this.#e("Invalid Request Query Params",e),new r("Invalid request query params",e);try{let d=e.query?`?${new URLSearchParams(e.query).toString()}`:"",b=this.#l({method:m,headers:{...this.#d(e.headers),...this.#u},body:e.body?typeof e.body=="string"?e.body:JSON.stringify(e.body):null,signal:a==null?void 0:a.signal}),g=e.path.charAt(0)!=="/"?`/${e.path}`:e.path;return this.#e("Fetch Options",{method:b.method,path:g,query:d}),fetch(`${this.#i}${g}${d}`,b).then(i=>{i.ok?o(i).then(u=>{this.#e("Response Success"),h(u)}).catch(u=>{this.#t("Response Parsing Error",u),c(new r("Error parsing response data",u))}):o(i).then(u=>{this.#e("Response Error",u),c(new r("Meshes API request failed",{status:i.status,statusText:i.statusText,data:u}))}).catch(u=>{this.#t("Response Parsing Failure",u),c(new r("Error parsing request failure",{status:i.status,statusText:i.statusText,error:u}))})}).catch(i=>{this.#t("Request Failure",i),c(new r("Request Failure",i))})}catch(d){throw this.#t("Unexpected Error",d),c(new r("Unexpected Error",d)),d}}).then(h=>{if(this.#e("Promise Success",h),t){this.#e("Promise Success","Callback Success"),t(null,h);return}return h}).catch(h=>{if(this.#e("Promise Error",h),t){this.#e("Promise Error","Callback Error"),t(h);return}throw h}).finally(()=>{l&&clearTimeout(l)});if(!t)return this.#e("Promise Returned","No callback"),I}emit(e,t={},s=void 0){return this.#n(e),this.#f({...this.#a,...t,path:"/events",method:"POST",body:e},s)}emitBatch(e,t={},s=void 0){if(!Array.isArray(e))throw new r("Events must be an array",e);if(e.length===0)throw new r("Events array cannot be empty");if(e.length>100)throw new r("Bulk emit supports up to 100 events per request",{count:e.length});for(let a of e)this.#n(a);return this.#f({...this.#a,...t,path:"/events/bulk",method:"POST",body:e},s)}},p=y;var O=p;export{r as MeshesApiError,p as MeshesEventsClient,O as default};
2
2
  /**
3
3
  * JavaScript Meshes Events Client
4
4
  * @module meshes-events-client
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@mesheshq/events",
3
- "version": "1.0.3",
3
+ "version": "1.0.4",
4
4
  "description": "Meshes events client for emitting events with a publishable key.",
5
5
  "author": "Todd Schlomer <todd@meshes.io> (https://meshes.io)",
6
6
  "license": "MIT",
7
7
  "type": "module",
8
8
  "main": "./dist/cjs/index.cjs",
9
9
  "module": "./dist/mjs/index.js",
10
+ "types": "./dist/index.d.ts",
10
11
  "exports": {
11
12
  ".": {
12
13
  "types": "./dist/index.d.ts",