@kenkaiiii/error-mom 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ken Kai
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,17 @@
1
+ # @kenkaiiii/error-mom
2
+
3
+ Automatic browser and Node.js error capture for a self-hosted Error Mom deployment.
4
+
5
+ ```ts
6
+ import { initErrorMom } from "@kenkaiiii/error-mom";
7
+
8
+ initErrorMom({
9
+ server: "https://errors.example.com",
10
+ projectKey: "em_ingest_...",
11
+ release: "1.0.0",
12
+ });
13
+ ```
14
+
15
+ Use `@kenkaiiii/error-mom/node` for Node.js. The browser adapter retries through local storage; the Node adapter writes a private JSONL spool before upload.
16
+
17
+ See the repository README for framework setup, privacy controls, and deployment instructions.
@@ -0,0 +1,86 @@
1
+ // src/shared.ts
2
+ var SDK_NAME = "@kenkaiiii/error-mom";
3
+ var SDK_VERSION = "0.1.0";
4
+ var MAX_BREADCRUMBS = 50;
5
+ var SECRET_KEY = /authorization|cookie|password|passwd|secret|token|api[-_]?key|session/i;
6
+ var URL_CREDENTIAL = /([?&](?:token|key|secret|password|code)=)[^&\s]*/gi;
7
+ var EMAIL = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi;
8
+ function redactString(value) {
9
+ return value.replace(URL_CREDENTIAL, "$1[REDACTED]").replace(EMAIL, "[REDACTED_EMAIL]");
10
+ }
11
+ function sanitize(value, depth = 0) {
12
+ if (depth > 5) return "[TRUNCATED]";
13
+ if (typeof value === "string") return redactString(value).slice(0, 1e4);
14
+ if (typeof value === "number" || typeof value === "boolean" || value === null) return value;
15
+ if (value instanceof Error) {
16
+ return {
17
+ name: value.name,
18
+ message: redactString(value.message),
19
+ stack: value.stack ? redactString(value.stack) : void 0
20
+ };
21
+ }
22
+ if (Array.isArray(value)) return value.slice(0, 50).map((item) => sanitize(item, depth + 1));
23
+ if (typeof value === "object" && value) {
24
+ return Object.fromEntries(
25
+ Object.entries(value).slice(0, 100).map(([key, item]) => [
26
+ key,
27
+ SECRET_KEY.test(key) ? "[REDACTED]" : sanitize(item, depth + 1)
28
+ ])
29
+ );
30
+ }
31
+ return String(value).slice(0, 2e3);
32
+ }
33
+ function printable(value) {
34
+ if (typeof value === "string") return redactString(value);
35
+ try {
36
+ return JSON.stringify(sanitize(value));
37
+ } catch {
38
+ return String(value);
39
+ }
40
+ }
41
+ function toError(value) {
42
+ if (value instanceof Error) return value;
43
+ if (typeof value === "string") return new Error(value);
44
+ return new Error(printable(value));
45
+ }
46
+ function platformName() {
47
+ if (typeof navigator !== "undefined") return navigator.platform || "browser";
48
+ return typeof process !== "undefined" ? process.platform : "unknown";
49
+ }
50
+ function createEvent(value, options, breadcrumbs, runtime, captureContext = {}) {
51
+ const error = toError(value);
52
+ const now = (/* @__PURE__ */ new Date()).toISOString();
53
+ return {
54
+ eventId: crypto.randomUUID(),
55
+ timestamp: now,
56
+ level: captureContext.level ?? "error",
57
+ error: {
58
+ name: redactString(error.name || "Error").slice(0, 500),
59
+ message: redactString(error.message || "Unknown error").slice(0, 1e4),
60
+ ...error.stack ? { stack: redactString(error.stack).slice(0, 1e5) } : {}
61
+ },
62
+ environment: options.environment ?? "production",
63
+ ...options.release ? { release: options.release } : {},
64
+ platform: platformName(),
65
+ runtime,
66
+ ...typeof location !== "undefined" ? { url: redactString(location.href) } : {},
67
+ ...captureContext.culprit ? { culprit: redactString(captureContext.culprit) } : {},
68
+ ...options.installationId ? { installationId: options.installationId } : {},
69
+ breadcrumbs: breadcrumbs.slice(-MAX_BREADCRUMBS),
70
+ tags: { ...options.tags, ...captureContext.tags },
71
+ context: sanitize(captureContext.context ?? {}) ?? {}
72
+ };
73
+ }
74
+ function endpoint(server) {
75
+ return `${server.replace(/\/$/, "")}/api/v1/events`;
76
+ }
77
+
78
+ export {
79
+ SDK_NAME,
80
+ SDK_VERSION,
81
+ MAX_BREADCRUMBS,
82
+ redactString,
83
+ printable,
84
+ createEvent,
85
+ endpoint
86
+ };
@@ -0,0 +1,20 @@
1
+ import { Breadcrumb } from '@kenkaiiii/error-mom-protocol';
2
+ export { Breadcrumb, ErrorEvent } from '@kenkaiiii/error-mom-protocol';
3
+ import { C as CommonOptions, a as CaptureContext } from './shared-idwux7-h.js';
4
+
5
+ interface BrowserOptions extends CommonOptions {
6
+ captureFailedRequests?: boolean;
7
+ flushIntervalMs?: number;
8
+ maxQueueSize?: number;
9
+ }
10
+ interface ErrorMomBrowser {
11
+ captureError(error: unknown, context?: CaptureContext): string;
12
+ addBreadcrumb(breadcrumb: Omit<Breadcrumb, "timestamp"> & {
13
+ timestamp?: string;
14
+ }): void;
15
+ flush(): Promise<void>;
16
+ dispose(): void;
17
+ }
18
+ declare function initErrorMom(options: BrowserOptions): ErrorMomBrowser;
19
+
20
+ export { type BrowserOptions, CaptureContext, type ErrorMomBrowser, initErrorMom };
package/dist/index.js ADDED
@@ -0,0 +1,187 @@
1
+ import {
2
+ MAX_BREADCRUMBS,
3
+ SDK_NAME,
4
+ SDK_VERSION,
5
+ createEvent,
6
+ endpoint,
7
+ printable,
8
+ redactString
9
+ } from "./chunk-ORM4B33R.js";
10
+
11
+ // src/index.ts
12
+ var clients = /* @__PURE__ */ new Map();
13
+ var BrowserClient = class {
14
+ options;
15
+ breadcrumbs = [];
16
+ queue = [];
17
+ flushPromise;
18
+ restore = [];
19
+ interval;
20
+ storageKey;
21
+ nativeFetch;
22
+ constructor(options) {
23
+ this.options = {
24
+ ...options,
25
+ captureConsoleErrors: options.captureConsoleErrors ?? true,
26
+ captureFailedRequests: options.captureFailedRequests ?? true,
27
+ flushIntervalMs: options.flushIntervalMs ?? 5e3,
28
+ maxQueueSize: options.maxQueueSize ?? 100
29
+ };
30
+ this.storageKey = `error-mom:${options.projectKey.slice(-12)}`;
31
+ this.restoreQueue();
32
+ this.installGlobalHandlers();
33
+ this.interval = setInterval(() => void this.flush(), this.options.flushIntervalMs);
34
+ void this.flush();
35
+ }
36
+ captureError(error, context = {}) {
37
+ const event = createEvent(error, this.options, this.breadcrumbs, "browser", context);
38
+ this.queue.push(event);
39
+ this.queue = this.queue.slice(-this.options.maxQueueSize);
40
+ this.persistQueue();
41
+ void this.flush();
42
+ return event.eventId;
43
+ }
44
+ addBreadcrumb(input) {
45
+ this.breadcrumbs.push({
46
+ ...input,
47
+ timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
48
+ message: redactString(input.message).slice(0, 2e3)
49
+ });
50
+ if (this.breadcrumbs.length > MAX_BREADCRUMBS) this.breadcrumbs.shift();
51
+ }
52
+ flush() {
53
+ if (this.flushPromise) return this.flushPromise;
54
+ if (this.queue.length === 0) return Promise.resolve();
55
+ this.flushPromise = this.sendBatch().finally(() => {
56
+ this.flushPromise = void 0;
57
+ });
58
+ return this.flushPromise;
59
+ }
60
+ async sendBatch() {
61
+ const batch = this.queue.slice(0, 20);
62
+ try {
63
+ const transport = this.nativeFetch ?? fetch;
64
+ const response = await transport(endpoint(this.options.server), {
65
+ method: "POST",
66
+ headers: {
67
+ "content-type": "application/json",
68
+ "x-error-mom-key": this.options.projectKey
69
+ },
70
+ body: JSON.stringify({ events: batch, sdk: { name: SDK_NAME, version: SDK_VERSION } }),
71
+ keepalive: true
72
+ });
73
+ if (!response.ok) return;
74
+ const accepted = new Set(batch.map((event) => event.eventId));
75
+ this.queue = this.queue.filter((event) => !accepted.has(event.eventId));
76
+ this.persistQueue();
77
+ } catch {
78
+ }
79
+ }
80
+ dispose() {
81
+ if (this.interval) clearInterval(this.interval);
82
+ for (const callback of this.restore.reverse()) callback();
83
+ clients.delete(this.options.projectKey);
84
+ }
85
+ installGlobalHandlers() {
86
+ if (typeof window === "undefined") return;
87
+ const onError = (event) => {
88
+ this.captureError(event.error ?? new Error(event.message), {
89
+ level: "fatal",
90
+ ...event.filename ? { culprit: `${event.filename}:${event.lineno}:${event.colno}` } : {}
91
+ });
92
+ };
93
+ const onRejection = (event) => {
94
+ this.captureError(event.reason, { culprit: "unhandledrejection" });
95
+ };
96
+ const onVisibility = () => {
97
+ if (document.visibilityState === "hidden") void this.flush();
98
+ };
99
+ window.addEventListener("error", onError);
100
+ window.addEventListener("unhandledrejection", onRejection);
101
+ document.addEventListener("visibilitychange", onVisibility);
102
+ this.restore.push(() => window.removeEventListener("error", onError));
103
+ this.restore.push(() => window.removeEventListener("unhandledrejection", onRejection));
104
+ this.restore.push(() => document.removeEventListener("visibilitychange", onVisibility));
105
+ this.captureConsole();
106
+ this.captureFetchFailures();
107
+ }
108
+ captureConsole() {
109
+ const levels = ["debug", "info", "warn", "error"];
110
+ for (const level of levels) {
111
+ const original = console[level].bind(console);
112
+ console[level] = (...args) => {
113
+ original(...args);
114
+ const message = args.map(printable).join(" ").slice(0, 2e3);
115
+ this.addBreadcrumb({
116
+ category: "console",
117
+ level: level === "warn" ? "warning" : level,
118
+ message
119
+ });
120
+ if (level === "error" && this.options.captureConsoleErrors) {
121
+ this.captureError(args[0] instanceof Error ? args[0] : new Error(message), {
122
+ culprit: "console.error"
123
+ });
124
+ }
125
+ };
126
+ this.restore.push(() => {
127
+ console[level] = original;
128
+ });
129
+ }
130
+ }
131
+ captureFetchFailures() {
132
+ if (!this.options.captureFailedRequests || typeof fetch === "undefined") return;
133
+ const original = fetch.bind(globalThis);
134
+ this.nativeFetch = original;
135
+ globalThis.fetch = async (input, init) => {
136
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
137
+ if (url.startsWith(this.options.server)) return original(input, init);
138
+ const method = init?.method ?? (input instanceof Request ? input.method : "GET");
139
+ try {
140
+ const response = await original(input, init);
141
+ if (response.status >= 500) {
142
+ this.captureError(
143
+ new Error(`${method} ${redactString(url)} returned ${response.status}`),
144
+ {
145
+ culprit: "fetch",
146
+ tags: { statusCode: String(response.status), method }
147
+ }
148
+ );
149
+ }
150
+ return response;
151
+ } catch (error) {
152
+ this.captureError(error, { culprit: "fetch", tags: { method, url: redactString(url) } });
153
+ throw error;
154
+ }
155
+ };
156
+ this.restore.push(() => {
157
+ globalThis.fetch = original;
158
+ });
159
+ }
160
+ restoreQueue() {
161
+ try {
162
+ const stored = localStorage.getItem(this.storageKey);
163
+ if (stored) this.queue = JSON.parse(stored);
164
+ } catch {
165
+ this.queue = [];
166
+ }
167
+ }
168
+ persistQueue() {
169
+ try {
170
+ localStorage.setItem(this.storageKey, JSON.stringify(this.queue));
171
+ } catch {
172
+ }
173
+ }
174
+ };
175
+ function initErrorMom(options) {
176
+ if (!options.server || !options.projectKey) {
177
+ throw new Error("Error Mom requires both server and projectKey");
178
+ }
179
+ const existing = clients.get(options.projectKey);
180
+ if (existing) return existing;
181
+ const client = new BrowserClient(options);
182
+ clients.set(options.projectKey, client);
183
+ return client;
184
+ }
185
+ export {
186
+ initErrorMom
187
+ };
package/dist/node.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { Breadcrumb } from '@kenkaiiii/error-mom-protocol';
2
+ export { Breadcrumb, ErrorEvent } from '@kenkaiiii/error-mom-protocol';
3
+ import { a as CaptureContext, C as CommonOptions } from './shared-idwux7-h.js';
4
+
5
+ interface NodeOptions extends CommonOptions {
6
+ spoolDirectory?: string;
7
+ flushIntervalMs?: number;
8
+ maxQueueSize?: number;
9
+ }
10
+ interface ErrorMomNode {
11
+ captureError(error: unknown, context?: CaptureContext): string;
12
+ addBreadcrumb(breadcrumb: Omit<Breadcrumb, "timestamp"> & {
13
+ timestamp?: string;
14
+ }): void;
15
+ flush(): Promise<void>;
16
+ dispose(): Promise<void>;
17
+ }
18
+ declare function initErrorMom(options: NodeOptions): ErrorMomNode;
19
+
20
+ export { CaptureContext, type ErrorMomNode, type NodeOptions, initErrorMom };
package/dist/node.js ADDED
@@ -0,0 +1,169 @@
1
+ import {
2
+ MAX_BREADCRUMBS,
3
+ SDK_NAME,
4
+ SDK_VERSION,
5
+ createEvent,
6
+ endpoint,
7
+ printable
8
+ } from "./chunk-ORM4B33R.js";
9
+
10
+ // src/node.ts
11
+ import { createHash } from "crypto";
12
+ import { mkdir, readFile, rename, writeFile, appendFile } from "fs/promises";
13
+ import { homedir } from "os";
14
+ import { join } from "path";
15
+ var NodeClient = class {
16
+ options;
17
+ breadcrumbs = [];
18
+ queue = [];
19
+ operation = Promise.resolve();
20
+ interval;
21
+ spoolFile;
22
+ handlers = [];
23
+ flushPromise;
24
+ constructor(options) {
25
+ this.options = {
26
+ ...options,
27
+ captureConsoleErrors: options.captureConsoleErrors ?? true,
28
+ flushIntervalMs: options.flushIntervalMs ?? 5e3,
29
+ maxQueueSize: options.maxQueueSize ?? 1e3,
30
+ spoolDirectory: options.spoolDirectory ?? join(homedir(), ".error-mom", "spool")
31
+ };
32
+ this.spoolFile = join(this.options.spoolDirectory, `${safeFilePart(options.projectKey)}.jsonl`);
33
+ this.operation = this.restoreQueue();
34
+ this.installProcessHandlers();
35
+ this.captureConsole();
36
+ this.interval = setInterval(() => void this.flush(), this.options.flushIntervalMs);
37
+ void this.flush();
38
+ }
39
+ captureError(error, context = {}) {
40
+ const event = createEvent(
41
+ error,
42
+ this.options,
43
+ this.breadcrumbs,
44
+ `node ${process.version}`,
45
+ context
46
+ );
47
+ this.queue.push(event);
48
+ this.queue = this.queue.slice(-this.options.maxQueueSize);
49
+ this.operation = this.operation.then(async () => {
50
+ await mkdir(this.options.spoolDirectory, { recursive: true });
51
+ await appendFile(this.spoolFile, `${JSON.stringify(event)}
52
+ `, { mode: 384 });
53
+ }).catch(() => void 0);
54
+ void this.flush();
55
+ return event.eventId;
56
+ }
57
+ addBreadcrumb(input) {
58
+ this.breadcrumbs.push({ ...input, timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString() });
59
+ if (this.breadcrumbs.length > MAX_BREADCRUMBS) this.breadcrumbs.shift();
60
+ }
61
+ flush() {
62
+ if (this.flushPromise) return this.flushPromise;
63
+ this.flushPromise = this.sendBatch().finally(() => {
64
+ this.flushPromise = void 0;
65
+ });
66
+ return this.flushPromise;
67
+ }
68
+ async sendBatch() {
69
+ await this.operation;
70
+ if (this.queue.length === 0) return;
71
+ const batch = this.queue.slice(0, 50);
72
+ try {
73
+ const response = await fetch(endpoint(this.options.server), {
74
+ method: "POST",
75
+ headers: {
76
+ "content-type": "application/json",
77
+ "x-error-mom-key": this.options.projectKey
78
+ },
79
+ body: JSON.stringify({ events: batch, sdk: { name: SDK_NAME, version: SDK_VERSION } })
80
+ });
81
+ if (!response.ok) return;
82
+ const accepted = new Set(batch.map((event) => event.eventId));
83
+ this.queue = this.queue.filter((event) => !accepted.has(event.eventId));
84
+ this.operation = this.operation.then(() => this.rewriteSpool());
85
+ await this.operation;
86
+ } catch {
87
+ }
88
+ }
89
+ async dispose() {
90
+ if (this.interval) clearInterval(this.interval);
91
+ for (const remove of this.handlers.reverse()) remove();
92
+ await this.flush();
93
+ if (singleton === this) singleton = void 0;
94
+ }
95
+ installProcessHandlers() {
96
+ const onUncaught = (error) => {
97
+ this.captureError(error, { level: "fatal", culprit: "uncaughtException" });
98
+ };
99
+ const onRejection = (reason) => {
100
+ this.captureError(reason, { culprit: "unhandledRejection" });
101
+ };
102
+ process.on("uncaughtExceptionMonitor", onUncaught);
103
+ process.on("unhandledRejection", onRejection);
104
+ this.handlers.push(() => process.off("uncaughtExceptionMonitor", onUncaught));
105
+ this.handlers.push(() => process.off("unhandledRejection", onRejection));
106
+ }
107
+ captureConsole() {
108
+ const levels = ["debug", "info", "warn", "error"];
109
+ for (const level of levels) {
110
+ const original = console[level].bind(console);
111
+ console[level] = (...args) => {
112
+ original(...args);
113
+ const message = args.map(printable).join(" ").slice(0, 2e3);
114
+ this.addBreadcrumb({
115
+ category: "console",
116
+ level: level === "warn" ? "warning" : level,
117
+ message
118
+ });
119
+ if (level === "error" && this.options.captureConsoleErrors) {
120
+ this.captureError(args[0] instanceof Error ? args[0] : new Error(message), {
121
+ culprit: "console.error"
122
+ });
123
+ }
124
+ };
125
+ this.handlers.push(() => {
126
+ console[level] = original;
127
+ });
128
+ }
129
+ }
130
+ async restoreQueue() {
131
+ try {
132
+ const contents = await readFile(this.spoolFile, "utf8");
133
+ const restored = contents.split("\n").filter(Boolean).flatMap((line) => {
134
+ try {
135
+ return [JSON.parse(line)];
136
+ } catch {
137
+ return [];
138
+ }
139
+ });
140
+ const merged = new Map(
141
+ [...restored, ...this.queue].map((event) => [event.eventId, event])
142
+ );
143
+ this.queue = [...merged.values()].slice(-this.options.maxQueueSize);
144
+ } catch {
145
+ }
146
+ }
147
+ async rewriteSpool() {
148
+ await mkdir(this.options.spoolDirectory, { recursive: true });
149
+ const temporary = `${this.spoolFile}.${process.pid}.tmp`;
150
+ const contents = this.queue.map((event) => JSON.stringify(event)).join("\n");
151
+ await writeFile(temporary, contents ? `${contents}
152
+ ` : "", { mode: 384 });
153
+ await rename(temporary, this.spoolFile);
154
+ }
155
+ };
156
+ function safeFilePart(projectKey) {
157
+ return createHash("sha256").update(projectKey).digest("hex").slice(0, 32);
158
+ }
159
+ var singleton;
160
+ function initErrorMom(options) {
161
+ if (!options.server || !options.projectKey) {
162
+ throw new Error("Error Mom requires both server and projectKey");
163
+ }
164
+ singleton ??= new NodeClient(options);
165
+ return singleton;
166
+ }
167
+ export {
168
+ initErrorMom
169
+ };
@@ -0,0 +1,19 @@
1
+ import { ErrorEvent } from '@kenkaiiii/error-mom-protocol';
2
+
3
+ interface CommonOptions {
4
+ server: string;
5
+ projectKey: string;
6
+ environment?: string;
7
+ release?: string;
8
+ installationId?: string;
9
+ tags?: Record<string, string>;
10
+ captureConsoleErrors?: boolean;
11
+ }
12
+ interface CaptureContext {
13
+ level?: ErrorEvent["level"];
14
+ culprit?: string;
15
+ tags?: Record<string, string>;
16
+ context?: Record<string, unknown>;
17
+ }
18
+
19
+ export type { CommonOptions as C, CaptureContext as a };
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@kenkaiiii/error-mom",
3
+ "version": "0.1.0",
4
+ "description": "Automatic browser and Node.js error capture for self-hosted Error Mom",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ },
13
+ "./node": {
14
+ "types": "./dist/node.d.ts",
15
+ "import": "./dist/node.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md"
21
+ ],
22
+ "dependencies": {
23
+ "@kenkaiiii/error-mom-protocol": "0.1.0"
24
+ },
25
+ "devDependencies": {
26
+ "tsup": "^8.5.1",
27
+ "vitest": "^4.1.10"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "license": "MIT",
33
+ "scripts": {
34
+ "build": "tsup src/index.ts src/node.ts --format esm --dts --clean",
35
+ "check": "tsc --noEmit",
36
+ "test": "vitest run"
37
+ }
38
+ }