@navikt/apm 0.0.0-stage → 0.7.3

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.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +527 -2
  3. package/dist/api.d.ts +108 -0
  4. package/dist/api.d.ts.map +1 -0
  5. package/dist/api.js +220 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/config.d.ts +150 -0
  8. package/dist/config.d.ts.map +1 -0
  9. package/dist/config.js +268 -0
  10. package/dist/config.js.map +1 -0
  11. package/dist/console.d.ts +28 -0
  12. package/dist/console.d.ts.map +1 -0
  13. package/dist/console.js +71 -0
  14. package/dist/console.js.map +1 -0
  15. package/dist/errors.d.ts +40 -0
  16. package/dist/errors.d.ts.map +1 -0
  17. package/dist/errors.js +177 -0
  18. package/dist/errors.js.map +1 -0
  19. package/dist/feedback.d.ts +42 -0
  20. package/dist/feedback.d.ts.map +1 -0
  21. package/dist/feedback.js +72 -0
  22. package/dist/feedback.js.map +1 -0
  23. package/dist/index.d.ts +144 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +249 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/internal.d.ts +47 -0
  28. package/dist/internal.d.ts.map +1 -0
  29. package/dist/internal.js +129 -0
  30. package/dist/internal.js.map +1 -0
  31. package/dist/metaTags.d.ts +34 -0
  32. package/dist/metaTags.d.ts.map +1 -0
  33. package/dist/metaTags.js +76 -0
  34. package/dist/metaTags.js.map +1 -0
  35. package/dist/react/ErrorBoundary.d.ts +59 -0
  36. package/dist/react/ErrorBoundary.d.ts.map +1 -0
  37. package/dist/react/ErrorBoundary.js +92 -0
  38. package/dist/react/ErrorBoundary.js.map +1 -0
  39. package/dist/react/NaisMetaTags.d.ts +25 -0
  40. package/dist/react/NaisMetaTags.d.ts.map +1 -0
  41. package/dist/react/NaisMetaTags.js +6 -0
  42. package/dist/react/NaisMetaTags.js.map +1 -0
  43. package/dist/react/index.d.ts +17 -0
  44. package/dist/react/index.d.ts.map +1 -0
  45. package/dist/react/index.js +14 -0
  46. package/dist/react/index.js.map +1 -0
  47. package/dist/react/nextClient.d.ts +25 -0
  48. package/dist/react/nextClient.d.ts.map +1 -0
  49. package/dist/react/nextClient.js +29 -0
  50. package/dist/react/nextClient.js.map +1 -0
  51. package/dist/react/routing.d.ts +56 -0
  52. package/dist/react/routing.d.ts.map +1 -0
  53. package/dist/react/routing.js +89 -0
  54. package/dist/react/routing.js.map +1 -0
  55. package/dist/replay/constants.d.ts +26 -0
  56. package/dist/replay/constants.d.ts.map +1 -0
  57. package/dist/replay/constants.js +24 -0
  58. package/dist/replay/constants.js.map +1 -0
  59. package/dist/replay/events.d.ts +74 -0
  60. package/dist/replay/events.d.ts.map +1 -0
  61. package/dist/replay/events.js +258 -0
  62. package/dist/replay/events.js.map +1 -0
  63. package/dist/replay/hash.d.ts +8 -0
  64. package/dist/replay/hash.d.ts.map +1 -0
  65. package/dist/replay/hash.js +14 -0
  66. package/dist/replay/hash.js.map +1 -0
  67. package/dist/replay/masking.d.ts +89 -0
  68. package/dist/replay/masking.d.ts.map +1 -0
  69. package/dist/replay/masking.js +199 -0
  70. package/dist/replay/masking.js.map +1 -0
  71. package/dist/replay/options.d.ts +52 -0
  72. package/dist/replay/options.d.ts.map +1 -0
  73. package/dist/replay/options.js +66 -0
  74. package/dist/replay/options.js.map +1 -0
  75. package/dist/replay/recording.d.ts +60 -0
  76. package/dist/replay/recording.d.ts.map +1 -0
  77. package/dist/replay/recording.js +120 -0
  78. package/dist/replay/recording.js.map +1 -0
  79. package/dist/replay/snapshot.d.ts +41 -0
  80. package/dist/replay/snapshot.d.ts.map +1 -0
  81. package/dist/replay/snapshot.js +97 -0
  82. package/dist/replay/snapshot.js.map +1 -0
  83. package/dist/replay/transport.d.ts +82 -0
  84. package/dist/replay/transport.d.ts.map +1 -0
  85. package/dist/replay/transport.js +188 -0
  86. package/dist/replay/transport.js.map +1 -0
  87. package/dist/scrub.d.ts +69 -0
  88. package/dist/scrub.d.ts.map +1 -0
  89. package/dist/scrub.js +317 -0
  90. package/dist/scrub.js.map +1 -0
  91. package/dist/serialize.d.ts +15 -0
  92. package/dist/serialize.d.ts.map +1 -0
  93. package/dist/serialize.js +68 -0
  94. package/dist/serialize.js.map +1 -0
  95. package/dist/tracing.d.ts +37 -0
  96. package/dist/tracing.d.ts.map +1 -0
  97. package/dist/tracing.js +70 -0
  98. package/dist/tracing.js.map +1 -0
  99. package/dist/version.d.ts +3 -0
  100. package/dist/version.d.ts.map +1 -0
  101. package/dist/version.js +3 -0
  102. package/dist/version.js.map +1 -0
  103. package/package.json +94 -4
package/dist/index.js ADDED
@@ -0,0 +1,249 @@
1
+ /**
2
+ * @nais/apm — opinionated Faro wrapper with a Sentry-like DX for nais apps.
3
+ *
4
+ * Root surface: `init`, `captureException`, `captureMessage`, `setUser`,
5
+ * `clearUser`, `setTag`, `setContext`, and opt-in browser tracing
6
+ * (`init({ tracing: true })`, lazily loaded). React helpers live in the
7
+ * separate `@nais/apm/react` entry point so this root stays free of React and
8
+ * the OpenTelemetry tracing tree.
9
+ */
10
+ import { ConsoleTransport, getWebInstrumentations, initializeFaro, } from '@grafana/faro-web-sdk';
11
+ import { fromNaisConfig, resolveConfig } from './config.js';
12
+ import { NaisConsoleInstrumentation } from './console.js';
13
+ import { FARO_ERRORS_INSTRUMENTATION_NAME, NaisErrorsInstrumentation } from './errors.js';
14
+ import { getStoredFaro, setFaroInstance, startPreInitBuffering } from './internal.js';
15
+ import { normalizeSessionReplay } from './replay/options.js';
16
+ import { composeBeforeSend } from './scrub.js';
17
+ export { captureException, captureMessage, setUser, clearUser, setTag, setContext, pushMeasurement, pushEvent, } from './api.js';
18
+ export { captureFeedback, FEEDBACK_EVENT_NAME } from './feedback.js';
19
+ export { resolveConfig, versionFromImage, fromNaisConfig, isLocalHost, navTenant } from './config.js';
20
+ export { getNaisMetaTags, renderNaisMetaTags } from './metaTags.js';
21
+ export { NaisConsoleInstrumentation, CONSOLE_ERROR_PREFIX } from './console.js';
22
+ export { NaisErrorsInstrumentation } from './errors.js';
23
+ export { scrubString } from './scrub.js';
24
+ export { isInitialized, markErrorCaptured } from './internal.js';
25
+ export { VERSION } from './version.js';
26
+ /**
27
+ * Default noise filters: browser-extension frames, benign ResizeObserver
28
+ * loops, and cross-origin "Script error." events without information.
29
+ */
30
+ export const DEFAULT_IGNORE_ERRORS = [
31
+ 'chrome-extension://',
32
+ 'moz-extension://',
33
+ 'safari-extension://',
34
+ 'safari-web-extension://',
35
+ /ResizeObserver loop (limit exceeded|completed with undelivered notifications)/,
36
+ /^Script error\.?$/,
37
+ ];
38
+ /**
39
+ * Initialize @nais/apm from a served nais generated-config file — the
40
+ * naiserator `spec.frontend.generatedConfig` payload mounted into the app's
41
+ * web root (nais/grafana-apm-app#134), or, later, the platform's well-known
42
+ * config URL. This is the zero-environment-config path for static SPAs: the
43
+ * fetched values fill any field not passed explicitly in `options`.
44
+ *
45
+ * Signals raised while the fetch is in flight (typically early errors) are
46
+ * buffered and flushed into Faro once initialization completes — they are not
47
+ * lost. If the fetch fails, initialization still proceeds with standard
48
+ * resolution (meta tags/env/fallbacks), which is loud about what is missing;
49
+ * this function never throws.
50
+ *
51
+ * @example
52
+ * // main.tsx — nais.json served from the web root via generatedConfig
53
+ * await initFromConfigUrl('/nais.json', { app: 'my-app', namespace: 'my-team' });
54
+ */
55
+ export async function initFromConfigUrl(url = '/nais.json', options = {}) {
56
+ const existing = getStoredFaro();
57
+ if (existing) {
58
+ // eslint-disable-next-line no-console
59
+ console.warn('[@nais/apm] init() called more than once; returning the existing instance.');
60
+ return existing;
61
+ }
62
+ startPreInitBuffering();
63
+ let fetched = {};
64
+ try {
65
+ const response = await fetch(url);
66
+ if (response.ok) {
67
+ fetched = fromNaisConfig((await response.json()));
68
+ }
69
+ else {
70
+ // eslint-disable-next-line no-console
71
+ console.warn(`[@nais/apm] Fetching nais config from '${url}' failed (HTTP ${response.status}); ` +
72
+ 'continuing with standard config resolution.');
73
+ }
74
+ }
75
+ catch {
76
+ // eslint-disable-next-line no-console
77
+ console.warn(`[@nais/apm] Fetching nais config from '${url}' failed (network error); ` +
78
+ 'continuing with standard config resolution.');
79
+ }
80
+ // Explicit options win over fetched values (resolution priority 1); the
81
+ // fetched config only fills fields the caller did not set.
82
+ const merged = { ...options };
83
+ for (const field of ['app', 'namespace', 'version', 'environment', 'telemetryUrl']) {
84
+ if (merged[field] == null && fetched[field] != null) {
85
+ merged[field] = fetched[field];
86
+ }
87
+ }
88
+ return init(merged);
89
+ }
90
+ /**
91
+ * Initialize @nais/apm. Zero-config on nais: app name, version, environment
92
+ * and collector URL are resolved from nais meta tags or build-time env; with
93
+ * no collector resolved (local dev) all telemetry is echoed to the console
94
+ * (silence that with `init({ devConsoleEcho: false })`).
95
+ *
96
+ * Opt into distributed tracing with `init({ tracing: true })`; the tracing
97
+ * machinery (`@grafana/faro-web-tracing`) is lazily loaded so it stays out of
98
+ * the bundle when tracing is not enabled.
99
+ */
100
+ export function init(options = {}) {
101
+ const existing = getStoredFaro();
102
+ if (existing) {
103
+ // eslint-disable-next-line no-console
104
+ console.warn('[@nais/apm] init() called more than once; returning the existing instance.');
105
+ return existing;
106
+ }
107
+ const config = resolveConfig(options);
108
+ const browserConfig = {
109
+ app: {
110
+ name: config.app,
111
+ // The nais team that owns this app. Faro's app model carries `namespace`,
112
+ // and the Alloy `faro.receiver` emits it as the `app_namespace` field on
113
+ // every log line — the label the plugin uses to attribute/filter browser
114
+ // telemetry by team (mirrors span metrics' `service_namespace`).
115
+ namespace: config.namespace,
116
+ version: config.version,
117
+ environment: config.environment,
118
+ // `release` mirrors `version` so exception grouping and release tagging
119
+ // in the Nais APM plugin line up with the deployed image.
120
+ release: config.version,
121
+ },
122
+ instrumentations: [
123
+ // captureConsole MUST stay false: NaisConsoleInstrumentation is the only
124
+ // console patch (see nais/grafana-apm-app#66). Faro's built-in
125
+ // ErrorsInstrumentation is excluded too: NaisErrorsInstrumentation is a
126
+ // drop-in replacement that additionally forwards `originalError` for
127
+ // unhandledrejection (window.onerror behavior is unchanged) — keeps
128
+ // exactly one window.onerror/unhandledrejection listener, avoiding a
129
+ // dedupe race with an originalError-less duplicate push.
130
+ ...getWebInstrumentations({ captureConsole: false }).filter((instrumentation) => instrumentation.name !== FARO_ERRORS_INSTRUMENTATION_NAME),
131
+ new NaisConsoleInstrumentation(),
132
+ new NaisErrorsInstrumentation(),
133
+ ],
134
+ ignoreErrors: [...DEFAULT_IGNORE_ERRORS, ...(options.ignoreErrors ?? [])],
135
+ // Dev mode defaults: echo to the console, or — with devConsoleEcho:
136
+ // false — an empty transport list (Faro accepts it; telemetry is
137
+ // dropped). Like every default here, the `faro` escape hatch spread
138
+ // below can still override `transports`.
139
+ ...(config.devMode
140
+ ? { transports: options.devConsoleEcho === false ? [] : [new ConsoleTransport()] }
141
+ : { url: config.telemetryUrl }),
142
+ ...options.faro,
143
+ beforeSend: composeBeforeSend(options.beforeSend ?? options.faro?.beforeSend, options.dangerouslyDisablePiiScrubbing === true),
144
+ };
145
+ // Replay/snapshot error trigger: the composed beforeSend sees every
146
+ // exception item regardless of capture path (uncaught, unhandledrejection,
147
+ // captureException, console capture) — one choke point. Multiple capture
148
+ // paths (events timeline, DOM recording, screenshot) may register a handler;
149
+ // each is invoked once per captured error.
150
+ const errorHandlers = [];
151
+ const composed = browserConfig.beforeSend;
152
+ browserConfig.beforeSend = (item) => {
153
+ const result = composed(item);
154
+ if (result && errorHandlers.length > 0 && item.type === 'exception') {
155
+ const payload = item.payload;
156
+ const message = String(payload?.value ?? '');
157
+ for (const handler of errorHandlers) {
158
+ handler(message);
159
+ }
160
+ }
161
+ return result;
162
+ };
163
+ const faro = initializeFaro(browserConfig);
164
+ setFaroInstance(faro);
165
+ // Opt-in browser tracing. Lazily imported (like replay) so faro-web-tracing
166
+ // and its OpenTelemetry dependency tree stay out of the bundle of apps that
167
+ // do not enable tracing. The mandatory header-propagation floor lives in
168
+ // tracing.ts and cannot be overridden here.
169
+ if (options.tracing) {
170
+ const tracingOptions = typeof options.tracing === 'object' ? options.tracing : undefined;
171
+ void import('./tracing.js')
172
+ .then(({ startTracing }) => startTracing(faro, {
173
+ propagateExtraOrigins: tracingOptions?.propagateExtraOrigins,
174
+ }))
175
+ .catch(() => { });
176
+ }
177
+ // Session-replay tier switch. `normalizeSessionReplay` applies the safe
178
+ // default tier (`events`), validates the enum, and warns the pilots affected
179
+ // by the masked-DOM → events default change.
180
+ const replay = normalizeSessionReplay(options.sessionReplay);
181
+ const wantScreenshot = options.screenshotOnError === true;
182
+ if (replay.enabled || wantScreenshot) {
183
+ const push = (name, attributes) => {
184
+ faro.api.pushEvent(name, attributes);
185
+ };
186
+ const sessionId = faro.api.getSession?.()?.id;
187
+ if (replay.enabled) {
188
+ if (replay.tier === 'dom') {
189
+ // Full masked DOM recording (rrweb) — personvernombud-gated.
190
+ void import('./replay/recording.js')
191
+ .then(({ startRecording }) => startRecording({
192
+ mode: replay.mode,
193
+ sampleRate: replay.sampleRate,
194
+ block: replay.block,
195
+ push,
196
+ sessionId,
197
+ }))
198
+ .then((handle) => {
199
+ if (handle) {
200
+ errorHandlers.push(() => handle.notifyError());
201
+ }
202
+ })
203
+ .catch(() => { });
204
+ }
205
+ else {
206
+ // events (default) and wireframe (Phase 3, currently falls back here):
207
+ // a DOM-free interaction timeline; no rrweb on this path.
208
+ void import('./replay/events.js')
209
+ .then(({ startEventsCollection }) => startEventsCollection({
210
+ mode: replay.mode,
211
+ sampleRate: replay.sampleRate,
212
+ push,
213
+ sessionId,
214
+ }))
215
+ .then((handle) => {
216
+ if (handle) {
217
+ errorHandlers.push(() => handle.notifyError());
218
+ }
219
+ })
220
+ .catch(() => { });
221
+ }
222
+ }
223
+ // screenshotOnError, folded into the tier model. A DOM snapshot is only
224
+ // produced when the DOM tier is explicitly chosen AND no full recording is
225
+ // already streaming checkouts; otherwise it degrades to a text-free
226
+ // events-tier breadcrumb. When a collector/recorder is already active for
227
+ // the session it owns error capture, so screenshotOnError adds nothing.
228
+ if (wantScreenshot && !replay.enabled) {
229
+ if (replay.tier === 'dom') {
230
+ void import('./replay/snapshot.js')
231
+ .then(({ captureSnapshot }) => {
232
+ errorHandlers.push((message) => {
233
+ void captureSnapshot(message, push, { block: replay.block });
234
+ });
235
+ })
236
+ .catch(() => { });
237
+ }
238
+ else {
239
+ void import('./replay/events.js')
240
+ .then(({ pushErrorBreadcrumb }) => {
241
+ errorHandlers.push(() => pushErrorBreadcrumb(push));
242
+ })
243
+ .catch(() => { });
244
+ }
245
+ }
246
+ }
247
+ return faro;
248
+ }
249
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EACL,gBAAgB,EAChB,sBAAsB,EACtB,cAAc,GACf,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAC1D,OAAO,EAAE,gCAAgC,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAC1F,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AACtF,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE/C,OAAO,EACL,gBAAgB,EAChB,cAAc,EACd,OAAO,EACP,SAAS,EACT,MAAM,EACN,UAAU,EACV,eAAe,EACf,SAAS,GACV,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAErE,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,cAAc,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAEt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,CAAC;YACrB,CAAC;QACH,CAAC;QAED,wEAAwE;QACxE,2EAA2E;QAC3E,oEAAoE;QACpE,0EAA0E;QAC1E,wEAAwE;QACxE,IAAI,cAAc,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACtC,IAAI,MAAM,CAAC,IAAI,KAAK,KAAK,EAAE,CAAC;gBAC1B,KAAK,MAAM,CAAC,sBAAsB,CAAC;qBAChC,IAAI,CAAC,CAAC,EAAE,eAAe,EAAE,EAAE,EAAE;oBAC5B,aAAa,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE;wBAC7B,KAAK,eAAe,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC;oBAC/D,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC;qBACD,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YACrB,CAAC;iBAAM,CAAC;gBACN,KAAK,MAAM,CAAC,oBAAoB,CAAC;qBAC9B,IAAI,CAAC,CAAC,EAAE,mBAAmB,EAAE,EAAE,EAAE;oBAChC,aAAa,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,mBAAmB,CAAC,IAAI,CAAC,CAAC,CAAC;gBACtD,CAAC,CAAC;qBACD,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YACrB,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,47 @@
1
+ /** @internal Shared module state between init() and the Sentry-compat API. */
2
+ import type { Faro } from '@grafana/faro-web-sdk';
3
+ export declare function setFaroInstance(faro: Faro | undefined): void;
4
+ /**
5
+ * @internal Start buffering capture calls until setFaroInstance runs. Used by
6
+ * initFromConfigUrl so signals raised while the config fetch is in flight
7
+ * (typically early errors) are not lost.
8
+ */
9
+ export declare function startPreInitBuffering(): void;
10
+ /**
11
+ * @internal Run `fn` now when initialized; buffer it when an async init is in
12
+ * flight; otherwise fall through to the warn-once no-op path.
13
+ */
14
+ export declare function runOrBuffer(fn: (faro: Faro) => void): void;
15
+ export declare function getFaroInstance(): Faro | undefined;
16
+ export declare function isInitialized(): boolean;
17
+ /** @internal Like getFaroInstance but never warns; for init()'s double-init path. */
18
+ export declare function getStoredFaro(): Faro | undefined;
19
+ export declare function getGlobalContext(): Record<string, string>;
20
+ /**
21
+ * Mark an error as owned by an explicit capture path, so
22
+ * `NaisConsoleInstrumentation` skips it when React logs it via
23
+ * `console.error`.
24
+ *
25
+ * Only needed if you have your own error boundary and call
26
+ * `captureException` from it instead of using `ApmErrorBoundary`. Call this
27
+ * from `getDerivedStateFromError` (NOT `componentDidCatch`) — React 19 logs
28
+ * caught errors through `console.error` before `componentDidCatch` runs, so
29
+ * marking it any later is too late to prevent a duplicate report:
30
+ *
31
+ * ```tsx
32
+ * static getDerivedStateFromError(error: Error) {
33
+ * markErrorCaptured(error);
34
+ * return { error };
35
+ * }
36
+ *
37
+ * componentDidCatch(error: Error, info: ErrorInfo) {
38
+ * captureException(error, { context: { componentStack: info.componentStack } });
39
+ * }
40
+ * ```
41
+ */
42
+ export declare function markErrorCaptured(error: unknown): void;
43
+ /** @internal True when {@link markErrorCaptured} has claimed this error. */
44
+ export declare function wasErrorCaptured(error: unknown): boolean;
45
+ /** @internal test helper */
46
+ export declare function _resetStateForTesting(): void;
47
+ //# sourceMappingURL=internal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"internal.d.ts","sourceRoot":"","sources":["../src/internal.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAE9E,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AA0BlD,wBAAgB,eAAe,CAAC,IAAI,EAAE,IAAI,GAAG,SAAS,GAAG,IAAI,CAY5D;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,IAAI,IAAI,CAI5C;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,EAAE,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,IAAI,GAAG,IAAI,CAY1D;AAED,wBAAgB,eAAe,IAAI,IAAI,GAAG,SAAS,CAOlD;AAED,wBAAgB,aAAa,IAAI,OAAO,CAEvC;AAED,qFAAqF;AACrF,wBAAgB,aAAa,IAAI,IAAI,GAAG,SAAS,CAEhD;AAED,wBAAgB,gBAAgB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAEzD;AAeD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAStD;AAED,4EAA4E;AAC5E,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAMxD;AAED,4BAA4B;AAC5B,wBAAgB,qBAAqB,IAAI,IAAI,CAM5C"}
@@ -0,0 +1,129 @@
1
+ /** @internal Shared module state between init() and the Sentry-compat API. */
2
+ /** Cap the pre-init buffer so a page that never finishes init can't grow it unbounded. */
3
+ const MAX_PENDING = 100;
4
+ const state = {
5
+ faro: undefined,
6
+ globalContext: {},
7
+ warnedNotInitialized: false,
8
+ buffering: false,
9
+ pending: [],
10
+ };
11
+ export function setFaroInstance(faro) {
12
+ state.faro = faro;
13
+ state.buffering = false;
14
+ if (faro && state.pending.length > 0) {
15
+ const pending = state.pending;
16
+ state.pending = [];
17
+ for (const fn of pending) {
18
+ fn(faro);
19
+ }
20
+ }
21
+ else {
22
+ state.pending = [];
23
+ }
24
+ }
25
+ /**
26
+ * @internal Start buffering capture calls until setFaroInstance runs. Used by
27
+ * initFromConfigUrl so signals raised while the config fetch is in flight
28
+ * (typically early errors) are not lost.
29
+ */
30
+ export function startPreInitBuffering() {
31
+ if (!state.faro) {
32
+ state.buffering = true;
33
+ }
34
+ }
35
+ /**
36
+ * @internal Run `fn` now when initialized; buffer it when an async init is in
37
+ * flight; otherwise fall through to the warn-once no-op path.
38
+ */
39
+ export function runOrBuffer(fn) {
40
+ if (state.faro) {
41
+ fn(state.faro);
42
+ return;
43
+ }
44
+ if (state.buffering) {
45
+ if (state.pending.length < MAX_PENDING) {
46
+ state.pending.push(fn);
47
+ }
48
+ return;
49
+ }
50
+ getFaroInstance(); // not initialized and not buffering: warn once, no-op
51
+ }
52
+ export function getFaroInstance() {
53
+ if (!state.faro && !state.warnedNotInitialized) {
54
+ state.warnedNotInitialized = true;
55
+ // eslint-disable-next-line no-console
56
+ console.warn('[@nais/apm] Called before init(); the call is a no-op. Call init() first.');
57
+ }
58
+ return state.faro;
59
+ }
60
+ export function isInitialized() {
61
+ return state.faro !== undefined;
62
+ }
63
+ /** @internal Like getFaroInstance but never warns; for init()'s double-init path. */
64
+ export function getStoredFaro() {
65
+ return state.faro;
66
+ }
67
+ export function getGlobalContext() {
68
+ return state.globalContext;
69
+ }
70
+ /**
71
+ * Marker for errors an explicit capture path already owns. React 19 logs every
72
+ * error caught by a boundary through `console.error` (the default
73
+ * `onCaughtError`, in dev AND prod builds) BEFORE calling `componentDidCatch`,
74
+ * so `NaisConsoleInstrumentation` would report it once and `ApmErrorBoundary`
75
+ * a second time (nais/apm#36). `ApmErrorBoundary` marks the error in
76
+ * `getDerivedStateFromError` — which runs before the console log — and the
77
+ * console capture path skips marked errors, leaving exactly one report.
78
+ *
79
+ * `Symbol.for` so two copies of this package in one bundle still agree.
80
+ */
81
+ const CAPTURED = Symbol.for('@nais/apm.captured');
82
+ /**
83
+ * Mark an error as owned by an explicit capture path, so
84
+ * `NaisConsoleInstrumentation` skips it when React logs it via
85
+ * `console.error`.
86
+ *
87
+ * Only needed if you have your own error boundary and call
88
+ * `captureException` from it instead of using `ApmErrorBoundary`. Call this
89
+ * from `getDerivedStateFromError` (NOT `componentDidCatch`) — React 19 logs
90
+ * caught errors through `console.error` before `componentDidCatch` runs, so
91
+ * marking it any later is too late to prevent a duplicate report:
92
+ *
93
+ * ```tsx
94
+ * static getDerivedStateFromError(error: Error) {
95
+ * markErrorCaptured(error);
96
+ * return { error };
97
+ * }
98
+ *
99
+ * componentDidCatch(error: Error, info: ErrorInfo) {
100
+ * captureException(error, { context: { componentStack: info.componentStack } });
101
+ * }
102
+ * ```
103
+ */
104
+ export function markErrorCaptured(error) {
105
+ if (typeof error !== 'object' || error === null) {
106
+ return;
107
+ }
108
+ try {
109
+ Object.defineProperty(error, CAPTURED, { value: true, configurable: true });
110
+ }
111
+ catch {
112
+ // Frozen/sealed error object: dedupe is best-effort, never fatal.
113
+ }
114
+ }
115
+ /** @internal True when {@link markErrorCaptured} has claimed this error. */
116
+ export function wasErrorCaptured(error) {
117
+ return (typeof error === 'object' &&
118
+ error !== null &&
119
+ error[CAPTURED] === true);
120
+ }
121
+ /** @internal test helper */
122
+ export function _resetStateForTesting() {
123
+ state.faro = undefined;
124
+ state.globalContext = {};
125
+ state.warnedNotInitialized = false;
126
+ state.buffering = false;
127
+ state.pending = [];
128
+ }
129
+ //# sourceMappingURL=internal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"internal.js","sourceRoot":"","sources":["../src/internal.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAiB9E,0FAA0F;AAC1F,MAAM,WAAW,GAAG,GAAG,CAAC;AAExB,MAAM,KAAK,GAAa;IACtB,IAAI,EAAE,SAAS;IACf,aAAa,EAAE,EAAE;IACjB,oBAAoB,EAAE,KAAK;IAC3B,SAAS,EAAE,KAAK;IAChB,OAAO,EAAE,EAAE;CACZ,CAAC;AAEF,MAAM,UAAU,eAAe,CAAC,IAAsB;IACpD,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC;IACxB,IAAI,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACrC,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;QAC9B,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC;QACnB,KAAK,MAAM,EAAE,IAAI,OAAO,EAAE,CAAC;YACzB,EAAE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ACH,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAC9C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QAChD,OAAO;IACT,CAAC;IACD,IAAI,CAAC;QACH,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9E,CAAC;IAAC,MAAM,CAAC;QACP,kEAAkE;IACpE,CAAC;AACH,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,gBAAgB,CAAC,KAAc;IAC7C,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACb,KAAiC,CAAC,QAAQ,CAAC,KAAK,IAAI,CACtD,CAAC;AACJ,CAAC;AAED,4BAA4B;AAC5B,MAAM,UAAU,qBAAqB;IACnC,KAAK,CAAC,IAAI,GAAG,SAAS,CAAC;IACvB,KAAK,CAAC,aAAa,GAAG,EAAE,CAAC;IACzB,KAAK,CAAC,oBAAoB,GAAG,KAAK,CAAC;IACnC,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC;IACxB,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC;AACrB,CAAC"}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Server-side meta-tag helpers (ADR-0001 decision 3, nais/grafana-apm-app#133
3
+ * phase 2): meta tags are the server→browser transport for frontend config,
4
+ * authored by the app's own server from the pod's runtime environment — the
5
+ * platform never injects them. These helpers make that authoring one line.
6
+ *
7
+ * Runs in Node (SSR): reads the `NAIS_*` runtime env naiserator injects into
8
+ * every pod, plus `NAIS_FRONTEND_TELEMETRY_COLLECTOR_URL` when
9
+ * `spec.frontend.generatedConfig` is enabled. In the browser it returns only
10
+ * whatever overrides were passed (there is no pod env to read).
11
+ */
12
+ import type { ConfigOptions, NaisGeneratedConfig } from './config.js';
13
+ export interface NaisMetaTag {
14
+ name: string;
15
+ content: string;
16
+ }
17
+ /**
18
+ * Resolve the five nais meta tags from explicit overrides, the optional
19
+ * naiserator generatedConfig payload, and the pod's runtime env — in that
20
+ * order. Fields that resolve to nothing are omitted (the browser-side
21
+ * resolution chain stays responsible for fallbacks and loudness).
22
+ *
23
+ * @example
24
+ * // Express: res.render('index', { naisMetaTags: renderNaisMetaTags() })
25
+ * // Custom templating:
26
+ * getNaisMetaTags().map(({ name, content }) => `<meta name="${name}" content="${content}">`)
27
+ */
28
+ export declare function getNaisMetaTags(overrides?: ConfigOptions, naisConfig?: NaisGeneratedConfig): NaisMetaTag[];
29
+ /**
30
+ * The same tags as {@link getNaisMetaTags}, rendered as an HTML string for
31
+ * string-based templating (Express/Handlebars/Thymeleaf-style SSR).
32
+ */
33
+ export declare function renderNaisMetaTags(overrides?: ConfigOptions, naisConfig?: NaisGeneratedConfig): string;
34
+ //# sourceMappingURL=metaTags.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metaTags.d.ts","sourceRoot":"","sources":["../src/metaTags.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEtE,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAaD;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAC7B,SAAS,GAAE,aAAkB,EAC7B,UAAU,CAAC,EAAE,mBAAmB,GAC/B,WAAW,EAAE,CAyBf;AAUD;;;GAGG;AACH,wBAAgB,kBAAkB,CAChC,SAAS,GAAE,aAAkB,EAC7B,UAAU,CAAC,EAAE,mBAAmB,GAC/B,MAAM,CAIR"}
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Server-side meta-tag helpers (ADR-0001 decision 3, nais/grafana-apm-app#133
3
+ * phase 2): meta tags are the server→browser transport for frontend config,
4
+ * authored by the app's own server from the pod's runtime environment — the
5
+ * platform never injects them. These helpers make that authoring one line.
6
+ *
7
+ * Runs in Node (SSR): reads the `NAIS_*` runtime env naiserator injects into
8
+ * every pod, plus `NAIS_FRONTEND_TELEMETRY_COLLECTOR_URL` when
9
+ * `spec.frontend.generatedConfig` is enabled. In the browser it returns only
10
+ * whatever overrides were passed (there is no pod env to read).
11
+ */
12
+ import { versionFromImage } from './config.js';
13
+ function env(name) {
14
+ try {
15
+ const value = process.env[name];
16
+ return value === '' ? undefined : value;
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
21
+ }
22
+ /**
23
+ * Resolve the five nais meta tags from explicit overrides, the optional
24
+ * naiserator generatedConfig payload, and the pod's runtime env — in that
25
+ * order. Fields that resolve to nothing are omitted (the browser-side
26
+ * resolution chain stays responsible for fallbacks and loudness).
27
+ *
28
+ * @example
29
+ * // Express: res.render('index', { naisMetaTags: renderNaisMetaTags() })
30
+ * // Custom templating:
31
+ * getNaisMetaTags().map(({ name, content }) => `<meta name="${name}" content="${content}">`)
32
+ */
33
+ export function getNaisMetaTags(overrides = {}, naisConfig) {
34
+ const fromConfig = naisConfig ?? {};
35
+ const app = overrides.app ?? fromConfig.app?.name ?? env('NAIS_APP_NAME');
36
+ const namespace = overrides.namespace ??
37
+ fromConfig.app?.namespace ??
38
+ env('NAIS_TEAM') ??
39
+ env('NAIS_NAMESPACE');
40
+ const environment = overrides.environment ?? fromConfig.environment ?? env('NAIS_CLUSTER_NAME');
41
+ // Runtime (pod) version identity: the image tag. GITHUB_SHA is a build-time
42
+ // concept and does not exist in the pod.
43
+ const version = overrides.version ?? fromConfig.app?.version ?? versionFromImage(env('NAIS_APP_IMAGE'));
44
+ const telemetryUrl = overrides.telemetryUrl ??
45
+ fromConfig.telemetryCollectorURL ??
46
+ env('NAIS_FRONTEND_TELEMETRY_COLLECTOR_URL');
47
+ const tags = [];
48
+ if (app)
49
+ tags.push({ name: 'nais-app', content: app });
50
+ if (namespace)
51
+ tags.push({ name: 'nais-team', content: namespace });
52
+ if (environment)
53
+ tags.push({ name: 'nais-cluster', content: environment });
54
+ if (version)
55
+ tags.push({ name: 'nais-version', content: version });
56
+ if (telemetryUrl)
57
+ tags.push({ name: 'nais-telemetry-url', content: telemetryUrl });
58
+ return tags;
59
+ }
60
+ function escapeAttribute(value) {
61
+ return value
62
+ .replaceAll('&', '&amp;')
63
+ .replaceAll('"', '&quot;')
64
+ .replaceAll('<', '&lt;')
65
+ .replaceAll('>', '&gt;');
66
+ }
67
+ /**
68
+ * The same tags as {@link getNaisMetaTags}, rendered as an HTML string for
69
+ * string-based templating (Express/Handlebars/Thymeleaf-style SSR).
70
+ */
71
+ export function renderNaisMetaTags(overrides = {}, naisConfig) {
72
+ return getNaisMetaTags(overrides, naisConfig)
73
+ .map(({ name, content }) => `<meta name="${name}" content="${escapeAttribute(content)}">`)
74
+ .join('\n');
75
+ }
76
+ //# sourceMappingURL=metaTags.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metaTags.js","sourceRoot":"","sources":["../src/metaTags.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAU/C,SAAS,GAAG,CAAC,IAAY;IACvB,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAChC,OAAO,KAAK,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC;IAC1C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,eAAe,CAC7B,SAAS,GAAkB,EAAE,EAC7B,UAAgC;IAEhC,MAAM,UAAU,GAAG,UAAU,IAAI,EAAE,C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AE,YAAY,EAAE,CAAC,CAAC;IACnF,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,eAAe,CAAC,KAAa;IACpC,OAAO,KAAK;SACT,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC;SACxB,UAAU,CAAC,GAAG,EAAE,QAAQ,CAAC;SACzB,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC;SACvB,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;AAC7B,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAChC,SAAS,GAAkB,EAAE,EAC7B,UAAgC;IAEhC,OAAO,eAAe,CAAC,SAAS,EAAE,UAAU,CAAC;SAC1C,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,eAAe,IAAI,cAAc,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC;SACzF,IAAI,CAAC,IAAI,CAAC,CAAC;AAChB,CAAC"}
@@ -0,0 +1,59 @@
1
+ /**
2
+ * React error boundary for @nais/apm (nais/grafana-apm-app#79).
3
+ *
4
+ * Why hand-rolled instead of wrapping faro-react's `FaroErrorBoundary`:
5
+ * `FaroErrorBoundary.componentDidCatch` unconditionally calls `api.pushError`
6
+ * itself. Routing a caught error through our `captureException` (to get the
7
+ * SDK's fingerprint/context pipeline) on top of that would report the SAME
8
+ * error twice. This boundary therefore owns the lifecycle and reports EXACTLY
9
+ * ONCE through `captureException`, so a render error gets our fingerprint and
10
+ * global context — and, as a bonus, the React entry stays free of faro-react's
11
+ * non-tree-shakeable barrel.
12
+ */
13
+ import { Component } from 'react';
14
+ import type { ComponentType, ErrorInfo, ReactNode } from 'react';
15
+ /** Render-prop fallback: receives the error and a reset callback. */
16
+ export type ApmErrorBoundaryFallbackRender = (error: Error, resetError: () => void) => ReactNode;
17
+ export interface ApmErrorBoundaryProps {
18
+ children?: ReactNode;
19
+ /**
20
+ * What to render once an error is caught. Either a React element/node, or a
21
+ * render function `(error, resetError) => node`. Defaults to a minimal
22
+ * `role="alert"` message.
23
+ */
24
+ fallback?: ReactNode | ApmErrorBoundaryFallbackRender;
25
+ /**
26
+ * Custom grouping key passed to `captureException` (mapped to
27
+ * `context.fingerprint`). A function receives the caught error so grouping
28
+ * can depend on it.
29
+ */
30
+ fingerprint?: string | ((error: Error) => string);
31
+ /** Extra context merged into the captured exception. */
32
+ context?: Record<string, unknown>;
33
+ /** Called after the error has been captured. */
34
+ onError?: (error: Error, errorInfo: ErrorInfo) => void;
35
+ /** Called when the boundary is reset (via the render-prop `resetError`). */
36
+ onReset?: (error: Error | null) => void;
37
+ }
38
+ interface ApmErrorBoundaryState {
39
+ error: Error | null;
40
+ }
41
+ /**
42
+ * Catches render errors in the subtree, reports them once through
43
+ * `captureException`, and renders a fallback. Sentry-compatible shape.
44
+ */
45
+ export declare class ApmErrorBoundary extends Component<ApmErrorBoundaryProps, ApmErrorBoundaryState> {
46
+ state: ApmErrorBoundaryState;
47
+ constructor(props: ApmErrorBoundaryProps);
48
+ static getDerivedStateFromError(error: Error): ApmErrorBoundaryState;
49
+ componentDidCatch(error: Error, errorInfo: ErrorInfo): void;
50
+ resetErrorBoundary(): void;
51
+ render(): ReactNode;
52
+ }
53
+ /**
54
+ * HOC that wraps a component in an {@link ApmErrorBoundary}. Sentry-compatible
55
+ * `withErrorBoundary` shape.
56
+ */
57
+ export declare function withApmErrorBoundary<P extends object>(WrappedComponent: ComponentType<P>, errorBoundaryProps?: ApmErrorBoundaryProps): ComponentType<P>;
58
+ export {};
59
+ //# sourceMappingURL=ErrorBoundary.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ErrorBoundary.d.ts","sourceRoot":"","sources":["../../src/react/ErrorBoundary.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,SAAS,EAAkB,MAAM,OAAO,CAAC;AAClD,OAAO,KAAK,EAAE,aAAa,EAAE,SAAS,EAAgB,SAAS,EAAE,MAAM,OAA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