@vestara-inc/node 0.1.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Ahsan Iqbal
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,187 @@
1
+ # Vestara Node.js SDK
2
+
3
+ Server-side Node.js SDK for Vestara crash reporting and remote logging.
4
+
5
+ **Requires Node.js 16+** — zero external runtime dependencies.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @vestara-inc/node
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ```typescript
16
+ import Vestara from '@vestara-inc/node';
17
+
18
+ Vestara.init({
19
+ token: 'your-project-token',
20
+ environment: 'production',
21
+ appVersion: '1.0.0',
22
+ targetCategory: 'web_backend',
23
+ serviceName: 'Node API',
24
+ appIdentifier: 'node-api',
25
+ // For background workers, use targetCategory: 'node_worker'
26
+ });
27
+
28
+ Vestara.log('info', 'Server started', { port: 3000 });
29
+ Vestara.setUser({ id: 'user-123', email: 'user@example.com' });
30
+
31
+ // Auto-captures uncaughtException and unhandledRejection
32
+ ```
33
+
34
+ ## Runtime target metadata
35
+
36
+ You can provide metadata to identify this application in the dashboard:
37
+ - `targetCategory`: The kind of target (e.g., `web_backend` for an API or `node_worker` for a queue processor).
38
+ - `serviceName`: Human-readable name (e.g., `Node API`).
39
+ - `appIdentifier`: Technical identifier (e.g., `node-api`).
40
+
41
+ ## API
42
+
43
+ ### `Vestara.init(options)`
44
+
45
+ Initializes the SDK. Safe to call more than once — restarts session and clears queue.
46
+
47
+ | Option | Type | Default |
48
+ |--------|------|---------|
49
+ | `token` | `string` | _(required)_ |
50
+ | `apiUrl` | `string` | `https://api.vestara.dev` |
51
+ | `environment` | `string` | `"production"` |
52
+ | `appVersion` | `string` | `"unknown"` |
53
+ | `targetCategory` | `string` | `"web_backend"` |
54
+ | `serviceName` | `string` | `undefined` |
55
+ | `appIdentifier` | `string` | `undefined` |
56
+ | `beforeSend` | `(event) => event \| null` | `undefined` |
57
+
58
+ ### `beforeSend` hook
59
+
60
+ The `beforeSend` option lets you inspect, modify, or drop events before they are queued:
61
+
62
+ ```typescript
63
+ Vestara.init({
64
+ token: 'your-project-token',
65
+ beforeSend: (event) => {
66
+ // Redact sensitive data
67
+ if (event.payload.data?.apiKey) {
68
+ const modified = { ...event, payload: { ...event.payload } };
69
+ modified.payload.data = { ...event.payload.data, apiKey: '[REDACTED]' };
70
+ return modified;
71
+ }
72
+
73
+ // Drop noisy health checks
74
+ if (event.payload.message === 'health-check') {
75
+ return null;
76
+ }
77
+
78
+ return event;
79
+ },
80
+ });
81
+ ```
82
+
83
+ Behavior:
84
+ - Return a modified event to send the modified version
85
+ - Return `null` to drop the event
86
+ - If the hook throws, the original event is sent (fail-open)
87
+
88
+ Note: The Vestara backend also applies server-side redaction as a safety layer.
89
+
90
+ ### `Vestara.log(level, message, data?)`
91
+
92
+ Queues a log event. Events are batched and sent every 10 seconds.
93
+
94
+ ```typescript
95
+ Vestara.log('error', 'Database connection failed', { host: 'db.local' });
96
+ ```
97
+
98
+ ### `Vestara.captureError(error, context?)`
99
+
100
+ Captures an error as a crash event with stack trace and breadcrumb snapshot. Triggers immediate flush.
101
+
102
+ ```typescript
103
+ try {
104
+ riskyOperation();
105
+ } catch (err) {
106
+ Vestara.captureError(err, { endpoint: '/api/users' });
107
+ }
108
+ ```
109
+
110
+ ### `Vestara.setUser(context)`
111
+
112
+ Attaches user context to subsequent events.
113
+
114
+ ```typescript
115
+ Vestara.setUser({ id: 'user-123', email: 'user@example.com' });
116
+ ```
117
+
118
+ ## Custom API URL
119
+
120
+ For local development, staging, or self-hosted deployments, pass `apiUrl`:
121
+
122
+ ```typescript
123
+ Vestara.init({
124
+ token: 'your-project-token',
125
+ apiUrl: 'http://localhost:3000',
126
+ environment: 'development',
127
+ });
128
+ ```
129
+
130
+ Do not set `apiUrl` for normal Vestara SaaS usage.
131
+
132
+ ## Automatic Behavior
133
+
134
+ ### Crash Capture
135
+
136
+ The SDK registers `process.on('uncaughtException')` and `process.on('unhandledRejection')` on first `init()`. Captured errors are sent with full stack traces and the current breadcrumb trail.
137
+
138
+ - After capturing an uncaughtException, the process exits with code `1`
139
+ - unhandledRejection errors are captured without crashing the process
140
+
141
+ ### Breadcrumbs
142
+
143
+ Every `Vestara.log()` call adds a breadcrumb. The last 50 breadcrumbs are attached to crash payloads.
144
+
145
+ ### Shutdown Flush
146
+
147
+ On `SIGTERM` or `SIGINT`, the SDK attempts a best-effort flush of remaining events (max 3 second wait). This is not guaranteed delivery.
148
+
149
+ ### Batching
150
+
151
+ - Max queue: 500 events (in-memory)
152
+ - Flush interval: 10 seconds
153
+ - Batch size: 100 events per request
154
+ - Crash events evict the oldest non-crash event when the queue is full
155
+ - Crash events trigger an immediate flush
156
+
157
+ ## Event Shape
158
+
159
+ All events include:
160
+
161
+ ```json
162
+ {
163
+ "event_type": "log" | "crash",
164
+ "session_id": "uuid",
165
+ "device_id": "uuid",
166
+ "timestamp": "ISO8601",
167
+ "sdk_version": "0.1.0",
168
+ "app_version": "string",
169
+ "os_name": "node",
170
+ "os_version": "v20.x.x",
171
+ "device_model": "darwin server",
172
+ "environment": "production",
173
+ "payload": { ... }
174
+ }
175
+ ```
176
+
177
+ ## No External Dependencies
178
+
179
+ Uses only Node.js built-ins: `crypto`, `http`, `https`, `process`, `url`.
180
+
181
+ ## License
182
+
183
+ This SDK is licensed under the Apache License 2.0.
184
+
185
+ Copyright 2026 Ahsan Iqbal.
186
+
187
+ Vestara, the Vestara name, logos, domain, and related branding are not granted under this license.
@@ -0,0 +1,12 @@
1
+ export interface Breadcrumb {
2
+ timestamp: string;
3
+ category: string;
4
+ message: string;
5
+ level: string;
6
+ data?: Record<string, unknown>;
7
+ }
8
+ export declare function addBreadcrumb(category: string, message: string, level: string, data?: Record<string, unknown>): void;
9
+ export declare function getBreadcrumbs(): Breadcrumb[];
10
+ export declare function clearBreadcrumbs(): void;
11
+ export declare function getBreadcrumbSnapshot(): Breadcrumb[];
12
+ //# sourceMappingURL=breadcrumbs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"breadcrumbs.d.ts","sourceRoot":"","sources":["../src/breadcrumbs.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,UAAU;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAChC;AAMD,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,EACb,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC7B,IAAI,CAcN;AAED,wBAAgB,cAAc,IAAI,UAAU,EAAE,CAE7C;AAED,wBAAgB,gBAAgB,IAAI,IAAI,CAEvC;AAED,wBAAgB,qBAAqB,IAAI,UAAU,EAAE,CAEpD"}
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addBreadcrumb = addBreadcrumb;
4
+ exports.getBreadcrumbs = getBreadcrumbs;
5
+ exports.clearBreadcrumbs = clearBreadcrumbs;
6
+ exports.getBreadcrumbSnapshot = getBreadcrumbSnapshot;
7
+ const BREADCRUMB_LIMIT = 50;
8
+ const buffer = [];
9
+ function addBreadcrumb(category, message, level, data) {
10
+ const breadcrumb = {
11
+ timestamp: new Date().toISOString(),
12
+ category,
13
+ message: message.slice(0, 200),
14
+ level,
15
+ data,
16
+ };
17
+ if (buffer.length >= BREADCRUMB_LIMIT) {
18
+ buffer.shift();
19
+ }
20
+ buffer.push(breadcrumb);
21
+ }
22
+ function getBreadcrumbs() {
23
+ return buffer.slice();
24
+ }
25
+ function clearBreadcrumbs() {
26
+ buffer.length = 0;
27
+ }
28
+ function getBreadcrumbSnapshot() {
29
+ return buffer.slice();
30
+ }
@@ -0,0 +1,28 @@
1
+ import * as queue from "./queue.js";
2
+ export type LogLevel = "debug" | "info" | "warn" | "error" | "fatal";
3
+ export type RuntimeTargetCategory = "ios_app" | "android_app" | "web_frontend" | "web_backend" | "react_native_app" | "flutter_app" | "python_worker" | "node_worker" | "desktop_app";
4
+ export interface InitOptions {
5
+ token: string;
6
+ apiUrl?: string;
7
+ environment?: string;
8
+ appVersion?: string;
9
+ targetCategory?: RuntimeTargetCategory;
10
+ serviceName?: string;
11
+ appIdentifier?: string;
12
+ beforeSend?: (event: queue.SDKEvent) => queue.SDKEvent | null;
13
+ }
14
+ export interface UserContext {
15
+ id: string;
16
+ email?: string;
17
+ }
18
+ export declare const Vestara: {
19
+ init(options: InitOptions): void;
20
+ log(level: LogLevel, message: string, data?: Record<string, unknown>): void;
21
+ captureError(error: unknown, context?: Record<string, unknown>): void;
22
+ setUser(context: UserContext): void;
23
+ setSession(): void;
24
+ __testonly__processUncaughtException(error: unknown): void;
25
+ __testonly__processUnhandledRejection(reason: unknown): void;
26
+ };
27
+ export default Vestara;
28
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AAGpC,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC;AAErE,MAAM,MAAM,qBAAqB,GAC7B,SAAS,GACT,aAAa,GACb,cAAc,GACd,aAAa,GACb,kBAAkB,GAClB,aAAa,GACb,eAAe,GACf,aAAa,GACb,aAAa,CAAC;AAElB,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,cAAc,CAAC,EAAE,qBAAqB,CAAC;IACvC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,QAAQ,KAAK,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC;CAC/D;AAED,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAmVD,eAAO,MAAM,OAAO;kBACJ,WAAW,GAAG,IAAI;eA8CrB,QAAQ,WAAW,MAAM,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;wBAiCvD,OAAO,YAAY,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;qBA0CpD,WAAW,GAAG,IAAI;kBAOrB,IAAI;gDAQ0B,OAAO,GAAG,IAAI;kDAIZ,OAAO,GAAG,IAAI;CAG7D,CAAC;AAEF,eAAe,OAAO,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,442 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.Vestara = void 0;
37
+ const http = __importStar(require("http"));
38
+ const https = __importStar(require("https"));
39
+ const metadata = __importStar(require("./metadata.js"));
40
+ const breadcrumbs = __importStar(require("./breadcrumbs.js"));
41
+ const queue = __importStar(require("./queue.js"));
42
+ const uploader = __importStar(require("./uploader.js"));
43
+ const DEFAULT_API_URL = "https://api.vestara.dev";
44
+ const DEFAULT_ENVIRONMENT = "production";
45
+ const DEVICE_SETTINGS_POLL_INTERVAL = 60000;
46
+ let config = null;
47
+ let initialized = false;
48
+ let user = null;
49
+ let handlersRegistered = false;
50
+ let shutdownRegistered = false;
51
+ let loggingEnabled = true;
52
+ let deviceSettingsTimer = null;
53
+ function makeEvent(eventType, payload) {
54
+ const base = metadata.getMetadata({
55
+ appVersion: config?.appVersion,
56
+ environment: config?.environment || DEFAULT_ENVIRONMENT,
57
+ });
58
+ return {
59
+ event_type: eventType,
60
+ session_id: base.session_id,
61
+ device_id: base.device_id,
62
+ timestamp: metadata.timestamp(),
63
+ sdk_version: base.sdk_version,
64
+ app_version: base.app_version,
65
+ os_name: base.os_name,
66
+ os_version: base.os_version,
67
+ device_model: base.device_model,
68
+ environment: base.environment,
69
+ target_category: config?.targetCategory || "web_backend",
70
+ ...(config?.serviceName ? { service_name: config.serviceName } : {}),
71
+ ...(config?.appIdentifier ? { app_identifier: config.appIdentifier } : {}),
72
+ payload,
73
+ };
74
+ }
75
+ function parseStack(stack) {
76
+ if (!stack) {
77
+ return [];
78
+ }
79
+ const lines = stack.split("\n");
80
+ const frames = [];
81
+ for (let i = 0; i < lines.length && frames.length < 30; i++) {
82
+ const raw = lines[i].trim();
83
+ if (!raw || raw === "Error") {
84
+ continue;
85
+ }
86
+ let match = null;
87
+ match = raw.match(/^\s*at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)$/);
88
+ if (match) {
89
+ frames.push({
90
+ function: match[1] || "(anonymous)",
91
+ file: match[2] || "unknown",
92
+ line: toNumber(match[3]),
93
+ column: toNumber(match[4]),
94
+ });
95
+ continue;
96
+ }
97
+ match = raw.match(/^\s*at\s+(.+?):(\d+):(\d+)$/);
98
+ if (match) {
99
+ frames.push({
100
+ function: "(anonymous)",
101
+ file: match[1] || "unknown",
102
+ line: toNumber(match[2]),
103
+ column: toNumber(match[3]),
104
+ });
105
+ continue;
106
+ }
107
+ match = raw.match(/^\s*at\s+(.+?)\s+\((.+?):(\d+)\)$/);
108
+ if (match) {
109
+ frames.push({
110
+ function: "(anonymous)",
111
+ file: match[2] || "unknown",
112
+ line: toNumber(match[3]),
113
+ });
114
+ continue;
115
+ }
116
+ match = raw.match(/^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);
117
+ if (match) {
118
+ frames.push({
119
+ function: match[1] || "(anonymous)",
120
+ file: match[2] || "unknown",
121
+ line: toNumber(match[3]),
122
+ column: toNumber(match[4]),
123
+ });
124
+ }
125
+ }
126
+ return frames;
127
+ }
128
+ function toNumber(value) {
129
+ const parsed = parseInt(value, 10);
130
+ return isNaN(parsed) ? 0 : parsed;
131
+ }
132
+ function normalizeValue(value) {
133
+ if (value === null || value === undefined) {
134
+ return undefined;
135
+ }
136
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
137
+ return value;
138
+ }
139
+ if (value instanceof Error) {
140
+ return value.message || String(value);
141
+ }
142
+ try {
143
+ return JSON.stringify(value);
144
+ }
145
+ catch {
146
+ return String(value);
147
+ }
148
+ }
149
+ function normalizeData(data) {
150
+ if (!data || typeof data !== "object") {
151
+ return undefined;
152
+ }
153
+ const result = {};
154
+ for (const [key, value] of Object.entries(data)) {
155
+ const normalized = normalizeValue(value);
156
+ if (normalized !== undefined) {
157
+ result[key] = normalized;
158
+ }
159
+ }
160
+ return Object.keys(result).length > 0 ? result : undefined;
161
+ }
162
+ async function pollDeviceSettings() {
163
+ if (!config) {
164
+ return;
165
+ }
166
+ const deviceId = metadata.getDeviceId();
167
+ if (!deviceId) {
168
+ return;
169
+ }
170
+ try {
171
+ const parsed = new URL(config.apiUrl + "/v1/sdk/device-settings?device_id=" + encodeURIComponent(deviceId));
172
+ const isHttps = parsed.protocol === "https:";
173
+ const transport = isHttps ? https : http;
174
+ const options = {
175
+ hostname: parsed.hostname,
176
+ port: parsed.port || (isHttps ? 443 : 80),
177
+ path: parsed.pathname + parsed.search,
178
+ method: "GET",
179
+ headers: {
180
+ "X-SDK-Token": config.token,
181
+ },
182
+ };
183
+ const response = await new Promise((resolve, reject) => {
184
+ const req = transport.request(options, resolve);
185
+ req.on("error", reject);
186
+ req.end();
187
+ });
188
+ if (response.statusCode === 200) {
189
+ const body = await new Promise((resolve) => {
190
+ let data = "";
191
+ response.on("data", (chunk) => { data += chunk; });
192
+ response.on("end", () => { resolve(data); });
193
+ });
194
+ const settings = JSON.parse(body);
195
+ if (typeof settings.logging_enabled === "boolean") {
196
+ loggingEnabled = settings.logging_enabled;
197
+ }
198
+ }
199
+ }
200
+ catch {
201
+ // fail open: continue with current loggingEnabled setting
202
+ }
203
+ }
204
+ function startDeviceSettingsPolling() {
205
+ if (deviceSettingsTimer) {
206
+ clearInterval(deviceSettingsTimer);
207
+ }
208
+ void pollDeviceSettings();
209
+ deviceSettingsTimer = setInterval(() => {
210
+ void pollDeviceSettings();
211
+ }, DEVICE_SETTINGS_POLL_INTERVAL);
212
+ }
213
+ function stopDeviceSettingsPolling() {
214
+ if (deviceSettingsTimer) {
215
+ clearInterval(deviceSettingsTimer);
216
+ deviceSettingsTimer = null;
217
+ }
218
+ }
219
+ function buildUserPayload() {
220
+ if (!user || !user.id) {
221
+ return undefined;
222
+ }
223
+ const payload = { id: user.id };
224
+ if (user.email) {
225
+ payload.email = user.email;
226
+ }
227
+ return payload;
228
+ }
229
+ function applyBeforeSend(event) {
230
+ if (!config?.beforeSend) {
231
+ return event;
232
+ }
233
+ try {
234
+ return config.beforeSend(event) ?? null;
235
+ }
236
+ catch {
237
+ return event;
238
+ }
239
+ }
240
+ function handleProcessError(error, contextType) {
241
+ if (!config)
242
+ return;
243
+ try {
244
+ const safeError = error instanceof Error ? error : new Error(String(error ?? "Unknown error"));
245
+ const stackTrace = parseStack(safeError.stack || "");
246
+ breadcrumbs.addBreadcrumb("process", `unhandled ${contextType}`, "error", {
247
+ message: safeError.message,
248
+ });
249
+ const payload = {
250
+ message: safeError.message || "Unknown error",
251
+ name: safeError.name || "Error",
252
+ stack: safeError.stack || "",
253
+ stack_trace: stackTrace,
254
+ context: { type: contextType },
255
+ };
256
+ const userPayload = buildUserPayload();
257
+ if (userPayload) {
258
+ payload.user = userPayload;
259
+ }
260
+ const snapshot = breadcrumbs.getBreadcrumbSnapshot();
261
+ if (snapshot.length > 0) {
262
+ payload.breadcrumbs = snapshot;
263
+ }
264
+ const event = makeEvent("crash", payload);
265
+ const finalEvent = applyBeforeSend(event);
266
+ if (finalEvent) {
267
+ queue.enqueue(finalEvent, true);
268
+ void uploader.flush(true).then(() => {
269
+ if (contextType === "uncaughtException") {
270
+ proc.exit(1);
271
+ }
272
+ });
273
+ }
274
+ else {
275
+ if (contextType === "uncaughtException") {
276
+ proc.exit(1);
277
+ }
278
+ }
279
+ }
280
+ catch {
281
+ // best-effort: re-throw if we can't capture
282
+ if (contextType === "uncaughtException") {
283
+ proc.exit(1);
284
+ }
285
+ }
286
+ }
287
+ const proc = typeof process !== "undefined" ? process : globalThis.process;
288
+ function registerHandlers() {
289
+ if (handlersRegistered) {
290
+ return;
291
+ }
292
+ handlersRegistered = true;
293
+ proc.on("unhandledRejection", (reason) => {
294
+ handleProcessError(reason, "unhandledRejection");
295
+ });
296
+ proc.on("uncaughtException", (error) => {
297
+ handleProcessError(error, "uncaughtException");
298
+ });
299
+ }
300
+ async function gracefulShutdown(signal) {
301
+ if (!config) {
302
+ return;
303
+ }
304
+ proc.removeAllListeners("SIGTERM");
305
+ proc.removeAllListeners("SIGINT");
306
+ stopDeviceSettingsPolling();
307
+ try {
308
+ await Promise.race([
309
+ uploader.flush(true),
310
+ new Promise((resolve) => setTimeout(resolve, 3000)),
311
+ ]);
312
+ }
313
+ catch {
314
+ // best-effort
315
+ }
316
+ if (signal === "SIGTERM") {
317
+ proc.kill(proc.pid, "SIGTERM");
318
+ }
319
+ else {
320
+ proc.exit(0);
321
+ }
322
+ }
323
+ exports.Vestara = {
324
+ init(options) {
325
+ if (!options || !options.token) {
326
+ return;
327
+ }
328
+ const wasInitialized = initialized;
329
+ config = {
330
+ token: options.token,
331
+ apiUrl: options.apiUrl || DEFAULT_API_URL,
332
+ environment: options.environment || DEFAULT_ENVIRONMENT,
333
+ appVersion: options.appVersion,
334
+ targetCategory: options.targetCategory || "web_backend",
335
+ serviceName: options.serviceName,
336
+ appIdentifier: options.appIdentifier,
337
+ beforeSend: options.beforeSend,
338
+ };
339
+ if (wasInitialized) {
340
+ uploader.stopUploader();
341
+ }
342
+ else {
343
+ registerHandlers();
344
+ }
345
+ if (!shutdownRegistered) {
346
+ shutdownRegistered = true;
347
+ proc.on("SIGTERM", () => { void gracefulShutdown("SIGTERM"); });
348
+ proc.on("SIGINT", () => { void gracefulShutdown("SIGINT"); });
349
+ }
350
+ uploader.initUploader({
351
+ apiUrl: config.apiUrl,
352
+ token: config.token,
353
+ });
354
+ if (wasInitialized) {
355
+ stopDeviceSettingsPolling();
356
+ }
357
+ startDeviceSettingsPolling();
358
+ breadcrumbs.clearBreadcrumbs();
359
+ queue.clear();
360
+ metadata.resetSessionId();
361
+ initialized = true;
362
+ },
363
+ log(level, message, data) {
364
+ if (!config || !message) {
365
+ return;
366
+ }
367
+ if (!loggingEnabled) {
368
+ return;
369
+ }
370
+ breadcrumbs.addBreadcrumb("log", message, level, data);
371
+ const payload = {
372
+ level,
373
+ message,
374
+ };
375
+ const normalized = normalizeData(data);
376
+ if (normalized) {
377
+ payload.data = normalized;
378
+ }
379
+ const userPayload = buildUserPayload();
380
+ if (userPayload) {
381
+ payload.user = userPayload;
382
+ }
383
+ const event = makeEvent("log", payload);
384
+ const finalEvent = applyBeforeSend(event);
385
+ if (finalEvent) {
386
+ queue.enqueue(finalEvent);
387
+ }
388
+ },
389
+ captureError(error, context) {
390
+ if (!config) {
391
+ return;
392
+ }
393
+ const safeError = error instanceof Error ? error : new Error(String(error ?? "Unknown error"));
394
+ const stackTrace = parseStack(safeError.stack || "");
395
+ breadcrumbs.addBreadcrumb("error", safeError.message, "error");
396
+ const payload = {
397
+ message: safeError.message || "Unknown error",
398
+ name: safeError.name || "Error",
399
+ stack: safeError.stack || "",
400
+ };
401
+ if (stackTrace.length > 0) {
402
+ payload.stack_trace = stackTrace;
403
+ }
404
+ if (context) {
405
+ payload.context = normalizeData(context);
406
+ }
407
+ const userPayload = buildUserPayload();
408
+ if (userPayload) {
409
+ payload.user = userPayload;
410
+ }
411
+ const snapshot = breadcrumbs.getBreadcrumbSnapshot();
412
+ if (snapshot.length > 0) {
413
+ payload.breadcrumbs = snapshot;
414
+ }
415
+ const event = makeEvent("crash", payload);
416
+ const finalEvent = applyBeforeSend(event);
417
+ if (finalEvent) {
418
+ queue.enqueue(finalEvent, true);
419
+ }
420
+ void uploader.flush(true);
421
+ },
422
+ setUser(context) {
423
+ if (!context || !context.id) {
424
+ return;
425
+ }
426
+ user = { id: context.id, email: context.email };
427
+ },
428
+ setSession() {
429
+ if (!config) {
430
+ return;
431
+ }
432
+ metadata.resetSessionId();
433
+ breadcrumbs.clearBreadcrumbs();
434
+ },
435
+ __testonly__processUncaughtException(error) {
436
+ handleProcessError(error, "uncaughtException");
437
+ },
438
+ __testonly__processUnhandledRejection(reason) {
439
+ handleProcessError(reason, "unhandledRejection");
440
+ },
441
+ };
442
+ exports.default = exports.Vestara;
@@ -0,0 +1,20 @@
1
+ export declare const SDK_VERSION = "0.1.0";
2
+ export declare function generateUUID(): string;
3
+ export declare function getDeviceId(): string;
4
+ export declare function getSessionId(): string;
5
+ export declare function resetSessionId(): void;
6
+ export declare function getMetadata(config: {
7
+ appVersion?: string;
8
+ environment: string;
9
+ }): {
10
+ device_id: string;
11
+ session_id: string;
12
+ sdk_version: string;
13
+ app_version: string;
14
+ os_name: string;
15
+ os_version: string;
16
+ device_model: string;
17
+ environment: string;
18
+ };
19
+ export declare function timestamp(): string;
20
+ //# sourceMappingURL=metadata.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metadata.d.ts","sourceRoot":"","sources":["../src/metadata.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,WAAW,UAAU,CAAC;AAKnC,wBAAgB,YAAY,IAAI,MAAM,CAYrC;AAED,wBAAgB,WAAW,IAAI,MAAM,CAKpC;AAED,wBAAgB,YAAY,IAAI,MAAM,CAKrC;AAED,wBAAgB,cAAc,IAAI,IAAI,CAErC;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE;IAClC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;CACrB,GAAG;IACF,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;CACrB,CAWA;AAED,wBAAgB,SAAS,IAAI,MAAM,CAElC"}
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.SDK_VERSION = void 0;
37
+ exports.generateUUID = generateUUID;
38
+ exports.getDeviceId = getDeviceId;
39
+ exports.getSessionId = getSessionId;
40
+ exports.resetSessionId = resetSessionId;
41
+ exports.getMetadata = getMetadata;
42
+ exports.timestamp = timestamp;
43
+ const crypto = __importStar(require("crypto"));
44
+ const process = __importStar(require("process"));
45
+ exports.SDK_VERSION = "0.1.0";
46
+ let _deviceId = null;
47
+ let _sessionId = null;
48
+ function generateUUID() {
49
+ const bytes = crypto.randomBytes(16);
50
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
51
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
52
+ const hex = bytes.toString("hex");
53
+ return (hex.slice(0, 8) + "-" +
54
+ hex.slice(8, 12) + "-" +
55
+ hex.slice(12, 16) + "-" +
56
+ hex.slice(16, 20) + "-" +
57
+ hex.slice(20));
58
+ }
59
+ function getDeviceId() {
60
+ if (!_deviceId) {
61
+ _deviceId = generateUUID();
62
+ }
63
+ return _deviceId;
64
+ }
65
+ function getSessionId() {
66
+ if (!_sessionId) {
67
+ _sessionId = generateUUID();
68
+ }
69
+ return _sessionId;
70
+ }
71
+ function resetSessionId() {
72
+ _sessionId = generateUUID();
73
+ }
74
+ function getMetadata(config) {
75
+ return {
76
+ device_id: getDeviceId(),
77
+ session_id: getSessionId(),
78
+ sdk_version: exports.SDK_VERSION,
79
+ app_version: config.appVersion || "unknown",
80
+ os_name: "node",
81
+ os_version: process.version,
82
+ device_model: process.platform + " server",
83
+ environment: config.environment,
84
+ };
85
+ }
86
+ function timestamp() {
87
+ return new Date().toISOString();
88
+ }
@@ -0,0 +1,23 @@
1
+ export interface SDKEvent {
2
+ event_type: string;
3
+ session_id: string;
4
+ device_id: string;
5
+ timestamp: string;
6
+ sdk_version: string;
7
+ app_version: string;
8
+ os_name: string;
9
+ os_version: string;
10
+ device_model: string;
11
+ environment: string;
12
+ target_category: string;
13
+ service_name?: string;
14
+ app_identifier?: string;
15
+ payload: Record<string, unknown>;
16
+ }
17
+ export declare function enqueue(event: SDKEvent, _immediate?: boolean): void;
18
+ export declare function peek(limit: number): SDKEvent[];
19
+ export declare function removeFirst(count: number): void;
20
+ export declare function count(): number;
21
+ export declare function getAll(): SDKEvent[];
22
+ export declare function clear(): void;
23
+ //# sourceMappingURL=queue.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queue.d.ts","sourceRoot":"","sources":["../src/queue.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,QAAQ;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC;AAMD,wBAAgB,OAAO,CAAC,KAAK,EAAE,QAAQ,EAAE,UAAU,CAAC,EAAE,OAAO,GAAG,IAAI,CA0BnE;AAED,wBAAgB,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,QAAQ,EAAE,CAE9C;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAE/C;AAED,wBAAgB,KAAK,IAAI,MAAM,CAE9B;AAED,wBAAgB,MAAM,IAAI,QAAQ,EAAE,CAEnC;AAED,wBAAgB,KAAK,IAAI,IAAI,CAE5B"}
package/dist/queue.js ADDED
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.enqueue = enqueue;
4
+ exports.peek = peek;
5
+ exports.removeFirst = removeFirst;
6
+ exports.count = count;
7
+ exports.getAll = getAll;
8
+ exports.clear = clear;
9
+ const QUEUE_LIMIT = 500;
10
+ const queue = [];
11
+ function enqueue(event, _immediate) {
12
+ if (event.event_type === "crash") {
13
+ if (queue.length < QUEUE_LIMIT) {
14
+ queue.push(event);
15
+ return;
16
+ }
17
+ const nonCrashIndex = queue.findIndex((e) => e.event_type !== "crash");
18
+ if (nonCrashIndex >= 0) {
19
+ queue.splice(nonCrashIndex, 1);
20
+ }
21
+ else {
22
+ queue.shift();
23
+ }
24
+ queue.push(event);
25
+ return;
26
+ }
27
+ if (queue.length >= QUEUE_LIMIT) {
28
+ const nonCrashIndex = queue.findIndex((e) => e.event_type !== "crash");
29
+ if (nonCrashIndex >= 0) {
30
+ queue.splice(nonCrashIndex, 1);
31
+ }
32
+ else {
33
+ return;
34
+ }
35
+ }
36
+ queue.push(event);
37
+ }
38
+ function peek(limit) {
39
+ return queue.slice(0, limit);
40
+ }
41
+ function removeFirst(count) {
42
+ queue.splice(0, count);
43
+ }
44
+ function count() {
45
+ return queue.length;
46
+ }
47
+ function getAll() {
48
+ return queue.slice();
49
+ }
50
+ function clear() {
51
+ queue.length = 0;
52
+ }
@@ -0,0 +1,10 @@
1
+ interface UploaderConfig {
2
+ apiUrl: string;
3
+ token: string;
4
+ }
5
+ export declare function initUploader(cfg: UploaderConfig): void;
6
+ export declare function stopUploader(): void;
7
+ export declare function flush(_immediate: boolean): Promise<void>;
8
+ export declare function isUploading(): boolean;
9
+ export {};
10
+ //# sourceMappingURL=uploader.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uploader.d.ts","sourceRoot":"","sources":["../src/uploader.ts"],"names":[],"mappings":"AAKA,UAAU,cAAc;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;CACf;AAMD,wBAAgB,YAAY,CAAC,GAAG,EAAE,cAAc,GAAG,IAAI,CAGtD;AAED,wBAAgB,YAAY,IAAI,IAAI,CAEnC;AAkBD,wBAAsB,KAAK,CAAC,UAAU,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAqC9D;AAiDD,wBAAgB,WAAW,IAAI,OAAO,CAErC"}
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.initUploader = initUploader;
37
+ exports.stopUploader = stopUploader;
38
+ exports.flush = flush;
39
+ exports.isUploading = isUploading;
40
+ const http = __importStar(require("http"));
41
+ const https = __importStar(require("https"));
42
+ const url_1 = require("url");
43
+ const queue = __importStar(require("./queue.js"));
44
+ let config = null;
45
+ let flushInterval = null;
46
+ let uploading = false;
47
+ function initUploader(cfg) {
48
+ config = cfg;
49
+ startFlushTimer();
50
+ }
51
+ function stopUploader() {
52
+ stopFlushTimer();
53
+ }
54
+ function startFlushTimer() {
55
+ if (flushInterval) {
56
+ clearInterval(flushInterval);
57
+ }
58
+ flushInterval = setInterval(() => {
59
+ void flush(false);
60
+ }, 10000);
61
+ }
62
+ function stopFlushTimer() {
63
+ if (flushInterval) {
64
+ clearInterval(flushInterval);
65
+ flushInterval = null;
66
+ }
67
+ }
68
+ async function flush(_immediate) {
69
+ if (!config) {
70
+ return;
71
+ }
72
+ if (uploading) {
73
+ return;
74
+ }
75
+ if (queue.count() === 0) {
76
+ return;
77
+ }
78
+ uploading = true;
79
+ try {
80
+ while (true) {
81
+ const batch = queue.peek(100);
82
+ if (batch.length === 0) {
83
+ break;
84
+ }
85
+ try {
86
+ await uploadBatch(config, batch);
87
+ }
88
+ catch {
89
+ break;
90
+ }
91
+ queue.removeFirst(batch.length);
92
+ if (queue.count() === 0) {
93
+ break;
94
+ }
95
+ }
96
+ }
97
+ finally {
98
+ uploading = false;
99
+ }
100
+ }
101
+ async function uploadBatch(cfg, events) {
102
+ return new Promise((resolve, reject) => {
103
+ let parsed;
104
+ try {
105
+ parsed = new url_1.URL(cfg.apiUrl + "/v1/ingest");
106
+ }
107
+ catch {
108
+ reject(new Error("Invalid API URL"));
109
+ return;
110
+ }
111
+ const isHttps = parsed.protocol === "https:";
112
+ const transport = isHttps ? https : http;
113
+ const body = JSON.stringify({ events });
114
+ const options = {
115
+ hostname: parsed.hostname,
116
+ port: parsed.port || (isHttps ? 443 : 80),
117
+ path: parsed.pathname + parsed.search,
118
+ method: "POST",
119
+ headers: {
120
+ "Content-Type": "application/json",
121
+ "X-SDK-Token": cfg.token,
122
+ "Content-Length": Buffer.byteLength(body),
123
+ },
124
+ };
125
+ const req = transport.request(options, (res) => {
126
+ if (res.statusCode === undefined || res.statusCode < 200 || res.statusCode >= 300) {
127
+ res.resume();
128
+ reject(new Error(`HTTP ${res.statusCode ?? "unknown"}`));
129
+ return;
130
+ }
131
+ res.resume();
132
+ resolve();
133
+ });
134
+ req.on("error", (err) => {
135
+ reject(err);
136
+ });
137
+ req.write(body);
138
+ req.end();
139
+ });
140
+ }
141
+ function isUploading() {
142
+ return uploading;
143
+ }
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@vestara-inc/node",
3
+ "version": "0.1.0",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "description": "Server-side Node.js SDK for Vestara",
8
+ "main": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js",
14
+ "require": "./dist/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "engines": {
21
+ "node": ">=16.0.0"
22
+ },
23
+ "scripts": {
24
+ "build": "tsc",
25
+ "typecheck": "tsc --noEmit",
26
+ "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --testTimeout=30000"
27
+ },
28
+ "license": "Apache-2.0",
29
+ "devDependencies": {
30
+ "@types/jest": "^30.0.0",
31
+ "@types/node": "^20.0.0",
32
+ "jest": "^29.7.0",
33
+ "ts-jest": "^29.4.9",
34
+ "typescript": "^5.0.0"
35
+ }
36
+ }