@mesheshq/events 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 CodeChop LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,237 @@
1
+ # meshes-events-client (@mesheshq/events)
2
+
3
+ [![Tests](https://github.com/mesheshq/node-meshes-events-client/actions/workflows/tests.yml/badge.svg)](https://github.com/mesheshq/node-meshes-events-client/actions/workflows/tests.yml)
4
+ [![NPM Version][npm-version-image]][npm-url]
5
+ [![NPM Install Size][npm-install-size-image]][npm-install-size-url]
6
+
7
+ A minimal JavaScript client for emitting events into **Meshes** using a **publishable key**.
8
+
9
+ This package is designed to be tiny and predictable:
10
+
11
+ - Supports **Promise**, **async/await**, and **callback** styles
12
+ - Works with both **ESM** and **CommonJS**
13
+ - Allows safe custom headers (with contract headers protected)
14
+ - Optional timeout support using `AbortController` when available
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm i @mesheshq/events
20
+ # or
21
+ pnpm add @mesheshq/events
22
+ # or
23
+ yarn add @mesheshq/events
24
+ ```
25
+
26
+ ## Quick Start
27
+
28
+ The package exports:
29
+
30
+ - `MeshesEventsClient` (default export + named export)
31
+ - `MeshesApiError`
32
+
33
+ ```js
34
+ // CommonJS
35
+ // const { MeshesEventsClient } = require("@mesheshq/events");
36
+
37
+ // ESM
38
+ import MeshesEventsClient, {
39
+ MeshesEventsClient as NamedClient,
40
+ } from "@mesheshq/events";
41
+
42
+ const publishableKey = process.env.WORKSPACE_PUBLISHABLE_KEY!;
43
+ const client = new MeshesEventsClient(publishableKey);
44
+
45
+ // Promise style
46
+ client
47
+ .emit({
48
+ event: "user.signed_up",
49
+ payload: { email: "a@b.com" },
50
+ })
51
+ .then((result) => {
52
+ // success handling
53
+ })
54
+ .catch((err) => {
55
+ // error handling
56
+ });
57
+
58
+ // Using async/await
59
+ try {
60
+ const result = await client.emit({
61
+ event: "user.signed_up",
62
+ payload: { email: "a@b.com" },
63
+ });
64
+
65
+ // success handling
66
+ } catch (err) {
67
+ // error handling
68
+ }
69
+ ```
70
+
71
+ ### Callback style (no Promise returned)
72
+
73
+ If you provide a callback, the method returns `undefined` and invokes the callback when complete.
74
+
75
+ ```js
76
+ client.emit(
77
+ { event: "user.signed_up", payload: { email: "a@b.com" } },
78
+ {},
79
+ function (err, result) {
80
+ if (err) {
81
+ // error handling
82
+ } else {
83
+ // success handling
84
+ }
85
+ }
86
+ );
87
+ ```
88
+
89
+ ## Publishable Key Format
90
+
91
+ Publishable keys can be found in the workspace settings and must be in a valid format
92
+
93
+ Example:
94
+
95
+ ```
96
+ mesh_pub_abc.def_ghi-jkl_asdf123
97
+ ```
98
+
99
+ If the publishable key is missing or invalid, the client throws a `MeshesApiError` immediately when constructing the client.
100
+
101
+ ## Usage
102
+
103
+ ### Initialization
104
+
105
+ ```js
106
+ import MeshesEventsClient from "@mesheshq/events";
107
+
108
+ const client = new MeshesEventsClient(process.env.WORKSPACE_PUBLISHABLE_KEY!, {
109
+ version: "v1", // only "v1" currently supported
110
+ timeout: 10000, // 1000..30000 ms
111
+ debug: false, // logs to console.debug / console.error when true
112
+
113
+ // Optional: extra default headers applied to all requests
114
+ headers: {
115
+ "X-Request-Id": "req_123",
116
+ },
117
+ });
118
+ ```
119
+
120
+ ### Emitting a Single Event
121
+
122
+ ```js
123
+ await client.emit({
124
+ event: "user.signed_up",
125
+ payload: {
126
+ email: "a@b.com",
127
+ name: "Test User",
128
+ },
129
+ });
130
+ ```
131
+
132
+ ### Emitting a Batch of Events
133
+
134
+ Batch requests support up to **100 events** per call.
135
+
136
+ ```js
137
+ await client.emitBatch([
138
+ { event: "user.signed_up", payload: { email: "a@b.com" } },
139
+ { event: "membership.started", payload: { email: "a@b.com", tier: "pro" } },
140
+ ]);
141
+ ```
142
+
143
+ ## Request Options
144
+
145
+ Both `emit()` and `emitBatch()` accept an optional `options` object:
146
+
147
+ ```js
148
+ await client.emit(
149
+ { event: "x", payload: { email: "a@b.com" } },
150
+ {
151
+ // Add request-specific headers
152
+ headers: {
153
+ "Idempotency-Key": "idem_456",
154
+ "X-Request-Id": "req_789",
155
+ },
156
+
157
+ // Override timeout for this call only (1000..30000 ms)
158
+ timeout: 15000,
159
+ }
160
+ );
161
+ ```
162
+
163
+ ### Protected / Forbidden Headers
164
+
165
+ To keep the API contract consistent, the following headers cannot be overridden via `options.headers`:
166
+
167
+ - `X-Meshes-Publishable-Key`
168
+ - `X-Meshes-Client`
169
+ - `Content-Type`
170
+ - `Accept`
171
+
172
+ If you pass these in **constructor** `headers`, the client throws a `MeshesApiError`.
173
+
174
+ If you pass them in **per-request** `options.headers`, they are silently dropped (and the client’s contract headers remain in effect).
175
+
176
+ ## Errors
177
+
178
+ All client errors are thrown as `MeshesApiError`.
179
+
180
+ ```js
181
+ import MeshesEventsClient, { MeshesApiError } from "@mesheshq/events";
182
+
183
+ try {
184
+ const client = new MeshesEventsClient(process.env.WORKSPACE_PUBLISHABLE_KEY!);
185
+ await client.emit({ event: "x", payload: { email: "a@b.com" } });
186
+ } catch (err) {
187
+ if (err instanceof MeshesApiError) {
188
+ // `err.data` may include HTTP status, response body, etc.
189
+ console.error("Meshes error:", err.message, err.data);
190
+ } else {
191
+ console.error("Unexpected error:", err);
192
+ }
193
+ }
194
+ ```
195
+
196
+ ### HTTP Failures
197
+
198
+ If the Meshes API returns a non-2xx response, the client throws `MeshesApiError` and includes:
199
+
200
+ ```js
201
+ err.data = {
202
+ status: 401,
203
+ statusText: "Unauthorized",
204
+ data: { ...parsedResponseBodyOrText },
205
+ };
206
+ ```
207
+
208
+ ## Response Body Parsing
209
+
210
+ Responses are parsed as:
211
+
212
+ - JSON (if the response body is valid JSON)
213
+ - otherwise plain text
214
+ - `null` if the response body is empty
215
+
216
+ ## Timeouts and AbortController
217
+
218
+ Timeout support uses `AbortController` when available (modern Node versions have it globally).
219
+ If `AbortController` is not available, requests still work, but timeouts cannot be enforced by aborting the request.
220
+
221
+ Timeout range: **1000ms** to **30000ms**.
222
+
223
+ ## Node / Runtime Notes
224
+
225
+ This client uses `fetch`. Ensure your runtime provides a global `fetch`:
226
+
227
+ - Node 18+ has global `fetch`
228
+ - For Node 16/17 you may need a polyfill (e.g. `undici`) or run in an environment that provides it
229
+
230
+ ## License
231
+
232
+ MIT
233
+
234
+ [npm-install-size-image]: https://badgen.net/packagephobia/publish/@mesheshq/events?cache=300
235
+ [npm-install-size-url]: https://packagephobia.com/result?p=%mesheshq%2Fevents
236
+ [npm-url]: https://www.npmjs.com/package/@mesheshq/events
237
+ [npm-version-image]: https://badgen.net/npm/v/@mesheshq/events?cache=300
@@ -0,0 +1,9 @@
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});
2
+ /**
3
+ * JavaScript Meshes Events Client
4
+ * @module meshes-events-client
5
+ * @license MIT
6
+ * @since 1.0.0
7
+ * @description Meshes events client for emitting events with a publishable key.
8
+ * @repository https://github.com/mesheshq/node-meshes-events-client
9
+ */
@@ -0,0 +1,140 @@
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
+ };
@@ -0,0 +1,9 @@
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};
2
+ /**
3
+ * JavaScript Meshes Events Client
4
+ * @module meshes-events-client
5
+ * @license MIT
6
+ * @since 1.0.0
7
+ * @description Meshes events client for emitting events with a publishable key.
8
+ * @repository https://github.com/mesheshq/node-meshes-events-client
9
+ */
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@mesheshq/events",
3
+ "version": "1.0.0",
4
+ "description": "Meshes events client for emitting events with a publishable key.",
5
+ "author": "Todd Schlomer <todd@meshes.io> (https://meshes.io)",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "main": "./dist/cjs/index.cjs",
9
+ "module": "./dist/mjs/index.js",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/mjs/index.js",
14
+ "require": "./dist/cjs/index.cjs"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/mesheshq/node-meshes-events-client"
23
+ },
24
+ "bugs": {
25
+ "url": "https://github.com/mesheshq/node-meshes-events-client/issues"
26
+ },
27
+ "homepage": "https://github.com/mesheshq/node-meshes-events-client#readme",
28
+ "scripts": {
29
+ "build": "rm -rf dist && node esbuild.js && tsc",
30
+ "watch": "npm run build -- --watch src",
31
+ "prepublishOnly": "npm run build",
32
+ "test": "vitest run --testTimeout 10000",
33
+ "test:watch": "vitest watch --testTimeout 10000",
34
+ "test:ci": "export CI=true && vitest run --coverage",
35
+ "coverage": "vitest run --coverage"
36
+ },
37
+ "dependencies": {},
38
+ "devDependencies": {
39
+ "@vitest/coverage-v8": "3.2.4",
40
+ "esbuild": "^0.27.2",
41
+ "esbuild-node-externals": "^1.20.1",
42
+ "prettier": "^3.2.5",
43
+ "typescript": "^5.1.6",
44
+ "vitest": "3.2.4"
45
+ },
46
+ "keywords": [
47
+ "Meshes",
48
+ "Meshes Events",
49
+ "Meshes Events Client"
50
+ ],
51
+ "engines": {
52
+ "node": ">=v18.20.8"
53
+ }
54
+ }