@molecule/api-error-tracking 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,115 @@
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
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=browser-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Browser guard — `@molecule/api-error-tracking` is SERVER-ONLY.
3
+ *
4
+ * Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
5
+ * Evaluating a server package in a browser bundle is always an import-graph mistake
6
+ * (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
7
+ * ("Buffer is not defined") far from the culprit. Throwing here names the package and
8
+ * the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
9
+ * unaffected: the throw requires browser globals AND the absence of a node runtime.
10
+ */
11
+ const g = globalThis;
12
+ if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
13
+ throw new Error('@molecule/api-error-tracking is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
14
+ 'from server code (a server route/function or your API), or dynamic-import it inside ' +
15
+ 'the server handler — never from components or shared client modules, and never ' +
16
+ 'polyfill Buffer/process to silence this.');
17
+ }
18
+ export {};
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Error tracking convenience functions.
3
+ *
4
+ * Unlike most core convenience modules, these NEVER throw:
5
+ *
6
+ * - When no provider is bonded they are a silent, documented no-op (returning
7
+ * `undefined` / `true`). Error tracking is a diagnostic side-channel — an
8
+ * app that hasn't wired a tracker must behave exactly as if the calls
9
+ * weren't there.
10
+ * - When the bonded provider itself throws, the failure is logged (warn) and
11
+ * swallowed for the same reason: a broken reporter must never take down the
12
+ * request or process it is reporting on.
13
+ *
14
+ * @module
15
+ */
16
+ import type { ErrorTrackingContext, ErrorTrackingLevel, ErrorTrackingUser } from './types.js';
17
+ /**
18
+ * Reports an exception (or any thrown value) to the bonded error tracking
19
+ * provider. Silent no-op when no provider is bonded; never throws.
20
+ *
21
+ * @param error - The thrown value to report.
22
+ * @param context - Optional normalized context (tags/user/extra/request).
23
+ * @returns The backend's event id when available, otherwise `undefined`.
24
+ */
25
+ export declare const captureException: (error: unknown, context?: ErrorTrackingContext) => string | undefined;
26
+ /**
27
+ * Reports a standalone message to the bonded error tracking provider.
28
+ * Silent no-op when no provider is bonded; never throws.
29
+ *
30
+ * @param message - The message to report.
31
+ * @param level - Severity level (providers default to `'info'` when omitted).
32
+ * @param context - Optional normalized context (tags/user/extra/request).
33
+ * @returns The backend's event id when available, otherwise `undefined`.
34
+ */
35
+ export declare const captureMessage: (message: string, level?: ErrorTrackingLevel, context?: ErrorTrackingContext) => string | undefined;
36
+ /**
37
+ * Associates subsequent captures with a user (`null` clears it). Silent
38
+ * no-op when no provider is bonded or the provider has no user scoping;
39
+ * never throws.
40
+ *
41
+ * @param user - The user to associate, or `null` to clear.
42
+ */
43
+ export declare const setUser: (user: ErrorTrackingUser | null) => void;
44
+ /**
45
+ * Flushes buffered events to the backend — call before process exit so
46
+ * queued reports aren't lost. Resolves `true` when no provider is bonded or
47
+ * the provider delivers synchronously (nothing to flush); never rejects.
48
+ *
49
+ * @param timeoutMs - Maximum time to wait for delivery.
50
+ * @returns `true` when everything flushed within the timeout.
51
+ */
52
+ export declare const flush: (timeoutMs?: number) => Promise<boolean>;
53
+ //# sourceMappingURL=error-tracking.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-tracking.d.ts","sourceRoot":"","sources":["../src/error-tracking.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH,OAAO,KAAK,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAI7F;;;;;;;GAOG;AACH,eAAO,MAAM,gBAAgB,GAC3B,OAAO,OAAO,EACd,UAAU,oBAAoB,KAC7B,MAAM,GAAG,SAaX,CAAA;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,cAAc,GACzB,SAAS,MAAM,EACf,QAAQ,kBAAkB,EAC1B,UAAU,oBAAoB,KAC7B,MAAM,GAAG,SAYX,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,OAAO,GAAI,MAAM,iBAAiB,GAAG,IAAI,KAAG,IAYxD,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,KAAK,GAAU,YAAY,MAAM,KAAG,OAAO,CAAC,OAAO,CAa/D,CAAA"}
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Error tracking convenience functions.
3
+ *
4
+ * Unlike most core convenience modules, these NEVER throw:
5
+ *
6
+ * - When no provider is bonded they are a silent, documented no-op (returning
7
+ * `undefined` / `true`). Error tracking is a diagnostic side-channel — an
8
+ * app that hasn't wired a tracker must behave exactly as if the calls
9
+ * weren't there.
10
+ * - When the bonded provider itself throws, the failure is logged (warn) and
11
+ * swallowed for the same reason: a broken reporter must never take down the
12
+ * request or process it is reporting on.
13
+ *
14
+ * @module
15
+ */
16
+ import { getLogger } from '@molecule/api-bond';
17
+ import { getOptionalProvider } from './provider.js';
18
+ const logger = getLogger();
19
+ /**
20
+ * Reports an exception (or any thrown value) to the bonded error tracking
21
+ * provider. Silent no-op when no provider is bonded; never throws.
22
+ *
23
+ * @param error - The thrown value to report.
24
+ * @param context - Optional normalized context (tags/user/extra/request).
25
+ * @returns The backend's event id when available, otherwise `undefined`.
26
+ */
27
+ export const captureException = (error, context) => {
28
+ const provider = getOptionalProvider();
29
+ // Documented no-op: no provider bonded means error tracking is not enabled
30
+ // for this app — behave as if the call weren't there.
31
+ if (!provider)
32
+ return undefined;
33
+ try {
34
+ return provider.captureException(error, context) ?? undefined;
35
+ }
36
+ catch (captureError) {
37
+ logger.warn('error-tracking: captureException failed — the report was not delivered', {
38
+ error: captureError,
39
+ });
40
+ return undefined;
41
+ }
42
+ };
43
+ /**
44
+ * Reports a standalone message to the bonded error tracking provider.
45
+ * Silent no-op when no provider is bonded; never throws.
46
+ *
47
+ * @param message - The message to report.
48
+ * @param level - Severity level (providers default to `'info'` when omitted).
49
+ * @param context - Optional normalized context (tags/user/extra/request).
50
+ * @returns The backend's event id when available, otherwise `undefined`.
51
+ */
52
+ export const captureMessage = (message, level, context) => {
53
+ const provider = getOptionalProvider();
54
+ // Documented no-op: see captureException.
55
+ if (!provider)
56
+ return undefined;
57
+ try {
58
+ return provider.captureMessage(message, level, context) ?? undefined;
59
+ }
60
+ catch (captureError) {
61
+ logger.warn('error-tracking: captureMessage failed — the report was not delivered', {
62
+ error: captureError,
63
+ });
64
+ return undefined;
65
+ }
66
+ };
67
+ /**
68
+ * Associates subsequent captures with a user (`null` clears it). Silent
69
+ * no-op when no provider is bonded or the provider has no user scoping;
70
+ * never throws.
71
+ *
72
+ * @param user - The user to associate, or `null` to clear.
73
+ */
74
+ export const setUser = (user) => {
75
+ const provider = getOptionalProvider();
76
+ // Documented no-op: see captureException. Also a no-op when the bonded
77
+ // provider doesn't implement optional user scoping.
78
+ if (!provider?.setUser)
79
+ return;
80
+ try {
81
+ provider.setUser(user);
82
+ }
83
+ catch (setUserError) {
84
+ logger.warn('error-tracking: setUser failed — user scoping was not applied', {
85
+ error: setUserError,
86
+ });
87
+ }
88
+ };
89
+ /**
90
+ * Flushes buffered events to the backend — call before process exit so
91
+ * queued reports aren't lost. Resolves `true` when no provider is bonded or
92
+ * the provider delivers synchronously (nothing to flush); never rejects.
93
+ *
94
+ * @param timeoutMs - Maximum time to wait for delivery.
95
+ * @returns `true` when everything flushed within the timeout.
96
+ */
97
+ export const flush = async (timeoutMs) => {
98
+ const provider = getOptionalProvider();
99
+ // Documented no-op: nothing bonded (or nothing buffered) means there is
100
+ // nothing to flush — report success.
101
+ if (!provider?.flush)
102
+ return true;
103
+ try {
104
+ return await provider.flush(timeoutMs);
105
+ }
106
+ catch (flushError) {
107
+ logger.warn('error-tracking: flush failed — buffered reports may be lost', {
108
+ error: flushError,
109
+ });
110
+ return false;
111
+ }
112
+ };
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Error tracking core interface for molecule.dev.
3
+ *
4
+ * Defines the standard interface for error tracking / crash reporting
5
+ * providers (Sentry, console, etc.) plus never-throwing convenience
6
+ * functions (`captureException`, `captureMessage`, `setUser`, `flush`)
7
+ * that delegate to the bonded provider.
8
+ *
9
+ * This is distinct from `@molecule/api-monitoring`, which is health checks
10
+ * (is the database up?). Error tracking captures individual unexpected
11
+ * exceptions with context so they can be aggregated and triaged.
12
+ *
13
+ * @module
14
+ * @example
15
+ * ```typescript
16
+ * import { setProvider, captureException, captureMessage } from '@molecule/api-error-tracking'
17
+ * import { provider } from '@molecule/api-error-tracking-sentry'
18
+ *
19
+ * // Bond a provider at startup (skip this and every capture is a no-op)
20
+ * setProvider(provider)
21
+ *
22
+ * // Report an unexpected exception with normalized context
23
+ * try {
24
+ * await chargeCustomer(order)
25
+ * } catch (error) {
26
+ * captureException(error, {
27
+ * tags: { source: 'billing' },
28
+ * user: { id: order.userId },
29
+ * extra: { orderId: order.id },
30
+ * })
31
+ * throw error
32
+ * }
33
+ *
34
+ * // Report a standalone message
35
+ * captureMessage('Payment retry queue is backing up', 'warning')
36
+ * ```
37
+ * @remarks
38
+ * - **The convenience functions NEVER throw and no-op when unbonded.** Error
39
+ * tracking is a diagnostic side-channel: an app without a bonded tracker
40
+ * (or with a broken one) must behave exactly as if the calls weren't
41
+ * there. Do NOT wrap `captureException` in defensive try/catch — it is
42
+ * already safe to call anywhere, including inside error middleware.
43
+ * - The default Express error path (`@molecule/api-server-default-express`)
44
+ * already calls `captureException` for genuine unexpected errors (untagged
45
+ * 500s, uncaught exceptions, unhandled rejections). Tagged config-missing
46
+ * 503s and 4xx responses are deliberately NOT captured — they are expected,
47
+ * user-actionable conditions, not defects.
48
+ * - `getProvider()` throws when unbonded (like other cores); prefer the
49
+ * convenience functions or `getOptionalProvider()` in reporting paths.
50
+ * - Context is normalized (`tags`/`user`/`extra`/`request`) — never pass
51
+ * provider-specific (e.g. Sentry) scope objects through this interface.
52
+ */
53
+ export * from './browser-guard.js';
54
+ export * from './error-tracking.js';
55
+ export * from './provider.js';
56
+ export * from './types.js';
57
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,qBAAqB,CAAA;AACnC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Error tracking core interface for molecule.dev.
3
+ *
4
+ * Defines the standard interface for error tracking / crash reporting
5
+ * providers (Sentry, console, etc.) plus never-throwing convenience
6
+ * functions (`captureException`, `captureMessage`, `setUser`, `flush`)
7
+ * that delegate to the bonded provider.
8
+ *
9
+ * This is distinct from `@molecule/api-monitoring`, which is health checks
10
+ * (is the database up?). Error tracking captures individual unexpected
11
+ * exceptions with context so they can be aggregated and triaged.
12
+ *
13
+ * @module
14
+ * @example
15
+ * ```typescript
16
+ * import { setProvider, captureException, captureMessage } from '@molecule/api-error-tracking'
17
+ * import { provider } from '@molecule/api-error-tracking-sentry'
18
+ *
19
+ * // Bond a provider at startup (skip this and every capture is a no-op)
20
+ * setProvider(provider)
21
+ *
22
+ * // Report an unexpected exception with normalized context
23
+ * try {
24
+ * await chargeCustomer(order)
25
+ * } catch (error) {
26
+ * captureException(error, {
27
+ * tags: { source: 'billing' },
28
+ * user: { id: order.userId },
29
+ * extra: { orderId: order.id },
30
+ * })
31
+ * throw error
32
+ * }
33
+ *
34
+ * // Report a standalone message
35
+ * captureMessage('Payment retry queue is backing up', 'warning')
36
+ * ```
37
+ * @remarks
38
+ * - **The convenience functions NEVER throw and no-op when unbonded.** Error
39
+ * tracking is a diagnostic side-channel: an app without a bonded tracker
40
+ * (or with a broken one) must behave exactly as if the calls weren't
41
+ * there. Do NOT wrap `captureException` in defensive try/catch — it is
42
+ * already safe to call anywhere, including inside error middleware.
43
+ * - The default Express error path (`@molecule/api-server-default-express`)
44
+ * already calls `captureException` for genuine unexpected errors (untagged
45
+ * 500s, uncaught exceptions, unhandled rejections). Tagged config-missing
46
+ * 503s and 4xx responses are deliberately NOT captured — they are expected,
47
+ * user-actionable conditions, not defects.
48
+ * - `getProvider()` throws when unbonded (like other cores); prefer the
49
+ * convenience functions or `getOptionalProvider()` in reporting paths.
50
+ * - Context is normalized (`tags`/`user`/`extra`/`request`) — never pass
51
+ * provider-specific (e.g. Sentry) scope objects through this interface.
52
+ */
53
+ export * from './browser-guard.js';
54
+ export * from './error-tracking.js';
55
+ export * from './provider.js';
56
+ export * from './types.js';
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Error tracking provider bond accessor.
3
+ *
4
+ * Bond packages (e.g. `@molecule/api-error-tracking-sentry`,
5
+ * `@molecule/api-error-tracking-console`) call `setProvider()` during setup.
6
+ * Application code uses the convenience functions from `error-tracking.ts`,
7
+ * which silently no-op when no provider is bonded — error tracking is an
8
+ * optional capability and reporting must never throw into the app.
9
+ *
10
+ * @module
11
+ */
12
+ import type { ErrorTrackingProvider } from './types.js';
13
+ /**
14
+ * Registers an error tracking provider as the active singleton. Called by
15
+ * bond packages during application startup.
16
+ *
17
+ * @param provider - The error tracking provider implementation to bond.
18
+ */
19
+ export declare const setProvider: (provider: ErrorTrackingProvider) => void;
20
+ /**
21
+ * Retrieves the bonded error tracking provider, throwing if none is
22
+ * configured. Application code should normally use the never-throwing
23
+ * convenience functions (`captureException`/`captureMessage`) or
24
+ * `getOptionalProvider()` instead.
25
+ *
26
+ * @returns The bonded error tracking provider.
27
+ * @throws {Error} If no error tracking provider has been bonded.
28
+ */
29
+ export declare const getProvider: () => ErrorTrackingProvider;
30
+ /**
31
+ * Checks whether an error tracking provider is currently bonded.
32
+ *
33
+ * @returns `true` if an error tracking provider is bonded.
34
+ */
35
+ export declare const hasProvider: () => boolean;
36
+ /**
37
+ * Retrieves the bonded error tracking provider, returning `null` if none is
38
+ * bonded. Prefer this over `getProvider()` in optional reporting code paths.
39
+ *
40
+ * @returns The bonded error tracking provider, or `null`.
41
+ */
42
+ export declare const getOptionalProvider: () => ErrorTrackingProvider | null;
43
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAKH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AAUvD;;;;;GAKG;AACH,eAAO,MAAM,WAAW,GAAI,UAAU,qBAAqB,KAAG,IAE7D,CAAA;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,WAAW,QAAO,qBAW9B,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,WAAW,QAAO,OAE9B,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,QAAO,qBAAqB,GAAG,IAE9D,CAAA"}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Error tracking provider bond accessor.
3
+ *
4
+ * Bond packages (e.g. `@molecule/api-error-tracking-sentry`,
5
+ * `@molecule/api-error-tracking-console`) call `setProvider()` during setup.
6
+ * Application code uses the convenience functions from `error-tracking.ts`,
7
+ * which silently no-op when no provider is bonded — error tracking is an
8
+ * optional capability and reporting must never throw into the app.
9
+ *
10
+ * @module
11
+ */
12
+ import { bond, get as bondGet, isBonded, require as bondRequire } from '@molecule/api-bond';
13
+ import { t } from '@molecule/api-i18n';
14
+ const BOND_TYPE = 'error-tracking';
15
+ // Deliberately NOT `expectBond(BOND_TYPE)`: error tracking is optional by
16
+ // design. The default Express server imports this core unconditionally (its
17
+ // error middleware reports through `captureException`), so marking the bond
18
+ // as expected would make `validateBonds()` fail every app that hasn't wired
19
+ // an error tracker. Unbonded apps must keep booting; the convenience
20
+ // functions in `error-tracking.ts` no-op instead.
21
+ /**
22
+ * Registers an error tracking provider as the active singleton. Called by
23
+ * bond packages during application startup.
24
+ *
25
+ * @param provider - The error tracking provider implementation to bond.
26
+ */
27
+ export const setProvider = (provider) => {
28
+ bond(BOND_TYPE, provider);
29
+ };
30
+ /**
31
+ * Retrieves the bonded error tracking provider, throwing if none is
32
+ * configured. Application code should normally use the never-throwing
33
+ * convenience functions (`captureException`/`captureMessage`) or
34
+ * `getOptionalProvider()` instead.
35
+ *
36
+ * @returns The bonded error tracking provider.
37
+ * @throws {Error} If no error tracking provider has been bonded.
38
+ */
39
+ export const getProvider = () => {
40
+ try {
41
+ return bondRequire(BOND_TYPE);
42
+ }
43
+ catch (error) {
44
+ throw new Error(t('errorTracking.error.noProvider', undefined, {
45
+ defaultValue: 'Error tracking provider not configured. Call setProvider() first.',
46
+ }), { cause: error });
47
+ }
48
+ };
49
+ /**
50
+ * Checks whether an error tracking provider is currently bonded.
51
+ *
52
+ * @returns `true` if an error tracking provider is bonded.
53
+ */
54
+ export const hasProvider = () => {
55
+ return isBonded(BOND_TYPE);
56
+ };
57
+ /**
58
+ * Retrieves the bonded error tracking provider, returning `null` if none is
59
+ * bonded. Prefer this over `getProvider()` in optional reporting code paths.
60
+ *
61
+ * @returns The bonded error tracking provider, or `null`.
62
+ */
63
+ export const getOptionalProvider = () => {
64
+ return bondGet(BOND_TYPE) ?? null;
65
+ };
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Error tracking core types for molecule.dev.
3
+ *
4
+ * Defines the standard, provider-agnostic interfaces for error tracking /
5
+ * crash reporting providers (Sentry, console, etc.). Every field here is
6
+ * normalized — no provider-specific types (e.g. Sentry's) leak into this
7
+ * contract, so swapping the bonded provider never changes consumer code.
8
+ *
9
+ * @module
10
+ */
11
+ /**
12
+ * Severity level for a captured message or exception.
13
+ */
14
+ export type ErrorTrackingLevel = 'fatal' | 'error' | 'warning' | 'info' | 'debug';
15
+ /**
16
+ * Normalized description of the user an event occurred for.
17
+ */
18
+ export interface ErrorTrackingUser {
19
+ /** Application-level user id. */
20
+ id?: string;
21
+ /** The user's email address. */
22
+ email?: string;
23
+ /** The user's username / display handle. */
24
+ username?: string;
25
+ /** The user's IP address. */
26
+ ipAddress?: string;
27
+ }
28
+ /**
29
+ * Normalized, provider-agnostic description of the HTTP request (or
30
+ * request-like operation) an event occurred in.
31
+ */
32
+ export interface ErrorTrackingRequestContext {
33
+ /** HTTP method (e.g. `GET`). */
34
+ method?: string;
35
+ /** Request URL or path, including the query string (e.g. `/api/users/123?full=true`). */
36
+ url?: string;
37
+ /**
38
+ * Selected request headers. Callers must NOT include credential-bearing
39
+ * headers (`cookie`, `authorization`) — error trackers are third-party
40
+ * sinks and must never receive session material.
41
+ */
42
+ headers?: Record<string, string | string[] | undefined>;
43
+ /** Parsed query parameters. */
44
+ query?: Record<string, unknown>;
45
+ }
46
+ /**
47
+ * Normalized context attached to a captured exception or message.
48
+ */
49
+ export interface ErrorTrackingContext {
50
+ /** Short, indexable key/value pairs (e.g. `{ source: 'express' }`). */
51
+ tags?: Record<string, string | number | boolean>;
52
+ /** The user the event occurred for. */
53
+ user?: ErrorTrackingUser;
54
+ /** Arbitrary additional (non-indexed) structured data. */
55
+ extra?: Record<string, unknown>;
56
+ /** The request the event occurred in. */
57
+ request?: ErrorTrackingRequestContext;
58
+ }
59
+ /**
60
+ * Error tracking provider interface.
61
+ *
62
+ * All error tracking providers must implement this interface. Providers
63
+ * receive the normalized {@link ErrorTrackingContext} and map it to their
64
+ * own event model (tags/user/extra scopes, etc.).
65
+ */
66
+ export interface ErrorTrackingProvider {
67
+ /**
68
+ * Reports an exception (or any thrown value) to the tracking backend.
69
+ *
70
+ * @param error - The thrown value to report.
71
+ * @param context - Optional normalized context (tags/user/extra/request).
72
+ * @returns The backend's event id when available, otherwise `undefined`.
73
+ */
74
+ captureException(error: unknown, context?: ErrorTrackingContext): string | void;
75
+ /**
76
+ * Reports a standalone message (no exception object) to the tracking backend.
77
+ *
78
+ * @param message - The message to report.
79
+ * @param level - Severity level (providers default to `'info'` when omitted).
80
+ * @param context - Optional normalized context (tags/user/extra/request).
81
+ * @returns The backend's event id when available, otherwise `undefined`.
82
+ */
83
+ captureMessage(message: string, level?: ErrorTrackingLevel, context?: ErrorTrackingContext): string | void;
84
+ /**
85
+ * Optionally associates subsequent captures with a user (`null` clears it).
86
+ * Providers whose backend has no user scoping may leave this undefined.
87
+ *
88
+ * @param user - The user to associate, or `null` to clear.
89
+ */
90
+ setUser?(user: ErrorTrackingUser | null): void;
91
+ /**
92
+ * Optionally flushes buffered events to the backend — call before process
93
+ * exit so queued reports aren't lost. Providers that deliver synchronously
94
+ * may leave this undefined.
95
+ *
96
+ * @param timeoutMs - Maximum time to wait for delivery.
97
+ * @returns `true` when everything flushed within the timeout.
98
+ */
99
+ flush?(timeoutMs?: number): Promise<boolean>;
100
+ }
101
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG,OAAO,GAAG,OAAO,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,CAAA;AAEjF;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,iCAAiC;IACjC,EAAE,CAAC,EAAE,MAAM,CAAA;IAEX,gCAAgC;IAChC,KAAK,CAAC,EAAE,MAAM,CAAA;IAEd,4CAA4C;IAC5C,QAAQ,CAAC,EAAE,MAAM,CAAA;IAEjB,6BAA6B;IAC7B,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB;AAED;;;GAGG;AACH,MAAM,WAAW,2BAA2B;IAC1C,gCAAgC;IAChC,MAAM,CAAC,EAAE,MAAM,CAAA;IAEf,yFAAyF;IACzF,GAAG,CAAC,EAAE,MAAM,CAAA;IAEZ;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAA;IAEvD,+BAA+B;IAC/B,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAChC;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC,uEAAuE;IACvE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAAA;IAEhD,uCAAuC;IACvC,IAAI,CAAC,EAAE,iBAAiB,CAAA;IAExB,0DAA0D;IAC1D,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAE/B,yCAAyC;IACzC,OAAO,CAAC,EAAE,2BAA2B,CAAA;CACtC;AAED;;;;;;GAMG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;;;;OAMG;IACH,gBAAgB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,MAAM,GAAG,IAAI,CAAA;IAE/E;;;;;;;OAOG;IACH,cAAc,CACZ,OAAO,EAAE,MAAM,EACf,KAAK,CAAC,EAAE,kBAAkB,EAC1B,OAAO,CAAC,EAAE,oBAAoB,GAC7B,MAAM,GAAG,IAAI,CAAA;IAEhB;;;;;OAKG;IACH,OAAO,CAAC,CAAC,IAAI,EAAE,iBAAiB,GAAG,IAAI,GAAG,IAAI,CAAA;IAE9C;;;;;;;OAOG;IACH,KAAK,CAAC,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;CAC7C"}
package/dist/types.js ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Error tracking core types for molecule.dev.
3
+ *
4
+ * Defines the standard, provider-agnostic interfaces for error tracking /
5
+ * crash reporting providers (Sentry, console, etc.). Every field here is
6
+ * normalized — no provider-specific types (e.g. Sentry's) leak into this
7
+ * contract, so swapping the bonded provider never changes consumer code.
8
+ *
9
+ * @module
10
+ */
11
+ export {};
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@molecule/api-error-tracking",
3
+ "version": "1.0.0",
4
+ "description": "Error tracking core interface for molecule.dev",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "vitest run",
11
+ "test:watch": "vitest"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "keywords": [
23
+ "molecule",
24
+ "error-tracking",
25
+ "errors",
26
+ "crash-reporting",
27
+ "monitoring"
28
+ ],
29
+ "license": "Apache-2.0",
30
+ "peerDependencies": {
31
+ "@molecule/api-bond": "^1.0.0",
32
+ "@molecule/api-i18n": "^1.0.0"
33
+ },
34
+ "devDependencies": {
35
+ "@molecule/api-bond": "1.0.0",
36
+ "@molecule/api-i18n": "1.0.0",
37
+ "@types/node": "26.1.2",
38
+ "typescript": "6.0.3",
39
+ "vitest": "4.1.10"
40
+ },
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "https://github.com/molecule-dev/molecule.git",
44
+ "directory": "packages/api/core/error-tracking"
45
+ },
46
+ "homepage": "https://github.com/molecule-dev/molecule/tree/main/packages/api/core/error-tracking",
47
+ "bugs": "https://github.com/molecule-dev/molecule/issues",
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }