@extn/segi-js 0.2.16 → 0.2.18

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.
@@ -0,0 +1,41 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/replay/token.ts
2
+ function withReplay(options = {}) {
3
+ return { __segi_replay: true, options };
4
+ }
5
+ function isObject(v) {
6
+ return !!v && typeof v === "object" && !Array.isArray(v);
7
+ }
8
+ function sanitizeReplayOptions(raw) {
9
+ if (!isObject(raw)) return {};
10
+ const out = {};
11
+ if (typeof raw.enabled === "boolean") out.enabled = raw.enabled;
12
+ const sample = typeof raw.sample === "string" ? Number(raw.sample) : raw.sample;
13
+ if (typeof sample === "number" && Number.isFinite(sample)) out.sample = sample;
14
+ if (Array.isArray(raw.blockRoutes)) {
15
+ out.blockRoutes = raw.blockRoutes.filter((p) => typeof p === "string");
16
+ }
17
+ if (isObject(raw.mask)) {
18
+ const mask = {};
19
+ if (raw.mask.inputs === "all" || raw.mask.inputs === "sensitive" || raw.mask.inputs === "none") {
20
+ mask.inputs = raw.mask.inputs;
21
+ }
22
+ if (typeof raw.mask.class === "string") mask.class = raw.mask.class;
23
+ out.mask = mask;
24
+ }
25
+ if (typeof raw.endpoint === "string" && raw.endpoint) out.endpoint = raw.endpoint;
26
+ if (typeof raw.trackRoutes === "boolean") out.trackRoutes = raw.trackRoutes;
27
+ return out;
28
+ }
29
+ function normalizeReplayToken(value) {
30
+ try {
31
+ if (!isObject(value) || value.__segi_replay !== true) return null;
32
+ return withReplay(sanitizeReplayOptions(value.options));
33
+ } catch (e) {
34
+ return null;
35
+ }
36
+ }
37
+
38
+
39
+
40
+
41
+ exports.withReplay = withReplay; exports.normalizeReplayToken = normalizeReplayToken;
@@ -0,0 +1,41 @@
1
+ // src/replay/token.ts
2
+ function withReplay(options = {}) {
3
+ return { __segi_replay: true, options };
4
+ }
5
+ function isObject(v) {
6
+ return !!v && typeof v === "object" && !Array.isArray(v);
7
+ }
8
+ function sanitizeReplayOptions(raw) {
9
+ if (!isObject(raw)) return {};
10
+ const out = {};
11
+ if (typeof raw.enabled === "boolean") out.enabled = raw.enabled;
12
+ const sample = typeof raw.sample === "string" ? Number(raw.sample) : raw.sample;
13
+ if (typeof sample === "number" && Number.isFinite(sample)) out.sample = sample;
14
+ if (Array.isArray(raw.blockRoutes)) {
15
+ out.blockRoutes = raw.blockRoutes.filter((p) => typeof p === "string");
16
+ }
17
+ if (isObject(raw.mask)) {
18
+ const mask = {};
19
+ if (raw.mask.inputs === "all" || raw.mask.inputs === "sensitive" || raw.mask.inputs === "none") {
20
+ mask.inputs = raw.mask.inputs;
21
+ }
22
+ if (typeof raw.mask.class === "string") mask.class = raw.mask.class;
23
+ out.mask = mask;
24
+ }
25
+ if (typeof raw.endpoint === "string" && raw.endpoint) out.endpoint = raw.endpoint;
26
+ if (typeof raw.trackRoutes === "boolean") out.trackRoutes = raw.trackRoutes;
27
+ return out;
28
+ }
29
+ function normalizeReplayToken(value) {
30
+ try {
31
+ if (!isObject(value) || value.__segi_replay !== true) return null;
32
+ return withReplay(sanitizeReplayOptions(value.options));
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ export {
39
+ withReplay,
40
+ normalizeReplayToken
41
+ };
package/dist/index.d.mts CHANGED
@@ -1,6 +1,29 @@
1
1
  import { SegiClientOptions, SegiEventDto, SegiUser, SegiBreadcrumb } from '@extn/segi-shared';
2
2
  export { SegiBreadcrumb, SegiClientOptions, SegiEventDto, SegiUser } from '@extn/segi-shared';
3
- import { R as ReplayConfig } from './types-CsgcNSc1.mjs';
3
+ import { R as ReplayConfig, a as ReplayOptions } from './types-BU4h40xl.mjs';
4
+
5
+ /**
6
+ * Turn whatever `captureException` was handed into an Error worth reporting,
7
+ * or `null` when there is nothing to report.
8
+ *
9
+ * Before this, every non-Error value became `new Error(JSON.stringify(v))`.
10
+ * For the common cases — an empty object from a third-party callback, an
11
+ * `undefined` rejection, a DOM Event — that produced "Error: {}" with no
12
+ * message, no culprit and an SDK-only stack. One production site generated
13
+ * 397k of those in five weeks, all from a chat-widget boot callback.
14
+ *
15
+ * Order of preference:
16
+ * 1. Error instances pass through untouched.
17
+ * 2. Strings / numbers / booleans become the message.
18
+ * 3. Event-like wrappers (`.error`, `.reason`) are unwrapped.
19
+ * 4. Error-like objects (`.message`, plus optional `.name` / `.code` /
20
+ * `.stack`) become an Error carrying those fields — covers DOMException
21
+ * in old engines, axios/fetch error shapes, GraphQL errors, etc.
22
+ * 5. Plain data objects are serialised (truncated) so the payload survives.
23
+ * 6. Anything that serialises to nothing (`{}`, `[]`, `null`, a cyclic
24
+ * object, a class instance with no own data) is dropped: `null`.
25
+ */
26
+ declare function normalizeError(value: unknown): Error | null;
4
27
 
5
28
  interface InitOptions {
6
29
  /** Re-initialize even if already initialized. Replaces config and listeners. */
@@ -46,6 +69,12 @@ declare const Segi: {
46
69
  * the duplicate-init warning.
47
70
  */
48
71
  init(options: SegiInitOptions, opts?: InitOptions): void;
72
+ /**
73
+ * Build the replay activation token for `Segi.init({ replay })`. Same as
74
+ * `withReplay` from `@extn/segi-js/replay`; on the CDN global it defaults
75
+ * `trackRoutes` to true.
76
+ */
77
+ withReplay(options?: ReplayOptions): ReplayConfig;
49
78
  /** True if init() has been called successfully on this bundle. */
50
79
  isInitialized(): boolean;
51
80
  /** Tear down listeners and reset state. Mostly for tests / hot-reload. */
@@ -57,4 +86,4 @@ declare const Segi: {
57
86
  addBreadcrumb(breadcrumb: SegiBreadcrumb): void;
58
87
  };
59
88
 
60
- export { type InitOptions, Segi, type SegiInitOptions, Segi as default };
89
+ export { type InitOptions, ReplayConfig, ReplayOptions, Segi, type SegiInitOptions, Segi as default, normalizeError };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,29 @@
1
1
  import { SegiClientOptions, SegiEventDto, SegiUser, SegiBreadcrumb } from '@extn/segi-shared';
2
2
  export { SegiBreadcrumb, SegiClientOptions, SegiEventDto, SegiUser } from '@extn/segi-shared';
3
- import { R as ReplayConfig } from './types-CsgcNSc1.js';
3
+ import { R as ReplayConfig, a as ReplayOptions } from './types-BU4h40xl.js';
4
+
5
+ /**
6
+ * Turn whatever `captureException` was handed into an Error worth reporting,
7
+ * or `null` when there is nothing to report.
8
+ *
9
+ * Before this, every non-Error value became `new Error(JSON.stringify(v))`.
10
+ * For the common cases — an empty object from a third-party callback, an
11
+ * `undefined` rejection, a DOM Event — that produced "Error: {}" with no
12
+ * message, no culprit and an SDK-only stack. One production site generated
13
+ * 397k of those in five weeks, all from a chat-widget boot callback.
14
+ *
15
+ * Order of preference:
16
+ * 1. Error instances pass through untouched.
17
+ * 2. Strings / numbers / booleans become the message.
18
+ * 3. Event-like wrappers (`.error`, `.reason`) are unwrapped.
19
+ * 4. Error-like objects (`.message`, plus optional `.name` / `.code` /
20
+ * `.stack`) become an Error carrying those fields — covers DOMException
21
+ * in old engines, axios/fetch error shapes, GraphQL errors, etc.
22
+ * 5. Plain data objects are serialised (truncated) so the payload survives.
23
+ * 6. Anything that serialises to nothing (`{}`, `[]`, `null`, a cyclic
24
+ * object, a class instance with no own data) is dropped: `null`.
25
+ */
26
+ declare function normalizeError(value: unknown): Error | null;
4
27
 
5
28
  interface InitOptions {
6
29
  /** Re-initialize even if already initialized. Replaces config and listeners. */
@@ -46,6 +69,12 @@ declare const Segi: {
46
69
  * the duplicate-init warning.
47
70
  */
48
71
  init(options: SegiInitOptions, opts?: InitOptions): void;
72
+ /**
73
+ * Build the replay activation token for `Segi.init({ replay })`. Same as
74
+ * `withReplay` from `@extn/segi-js/replay`; on the CDN global it defaults
75
+ * `trackRoutes` to true.
76
+ */
77
+ withReplay(options?: ReplayOptions): ReplayConfig;
49
78
  /** True if init() has been called successfully on this bundle. */
50
79
  isInitialized(): boolean;
51
80
  /** Tear down listeners and reset state. Mostly for tests / hot-reload. */
@@ -57,4 +86,4 @@ declare const Segi: {
57
86
  addBreadcrumb(breadcrumb: SegiBreadcrumb): void;
58
87
  };
59
88
 
60
- export { type InitOptions, Segi, type SegiInitOptions, Segi as default };
89
+ export { type InitOptions, ReplayConfig, ReplayOptions, Segi, type SegiInitOptions, Segi as default, normalizeError };
package/dist/index.js CHANGED
@@ -1,4 +1,9 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/core.ts
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+ var _chunkUSYEDAPQjs = require('./chunk-USYEDAPQ.js');
5
+
6
+ // src/core.ts
2
7
  var DEFAULT_MAX_BREADCRUMBS = 50;
3
8
  function createState() {
4
9
  return {
@@ -47,7 +52,7 @@ function buildEvent(state2, base) {
47
52
  return { ...evt, _drop: true };
48
53
  }
49
54
  return next;
50
- } catch (e) {
55
+ } catch (e2) {
51
56
  return evt;
52
57
  }
53
58
  }
@@ -130,8 +135,106 @@ function send(endpoint, projectKey, event) {
130
135
  const blob = new Blob([body], { type: "application/json" });
131
136
  navigator.sendBeacon(beaconUrl, blob);
132
137
  }
133
- } catch (e2) {
138
+ } catch (e3) {
139
+ }
140
+ }
141
+
142
+ // src/normalize-error.ts
143
+ var MAX_JSON_MESSAGE = 1e3;
144
+ function str(v) {
145
+ return typeof v === "string" && v.trim().length > 0 ? v : null;
146
+ }
147
+ function withMeta(e, o) {
148
+ const name = _nullishCoalesce(str(o.name), () => ( (typeof o.code === "string" ? o.code : null)));
149
+ if (name) {
150
+ try {
151
+ e.name = name;
152
+ } catch (e4) {
153
+ }
154
+ }
155
+ const stack = str(o.stack);
156
+ if (stack) {
157
+ try {
158
+ e.stack = stack;
159
+ } catch (e5) {
160
+ }
161
+ }
162
+ return e;
163
+ }
164
+ function hasContent(v, depth = 0, seen = /* @__PURE__ */ new Set()) {
165
+ if (v === null || v === void 0) return false;
166
+ switch (typeof v) {
167
+ case "string":
168
+ return v.trim().length > 0;
169
+ case "number":
170
+ case "boolean":
171
+ case "bigint":
172
+ return true;
173
+ case "object":
174
+ break;
175
+ default:
176
+ return false;
177
+ }
178
+ if (depth > 4 || seen.has(v)) return false;
179
+ seen.add(v);
180
+ try {
181
+ for (const k of Object.keys(v)) {
182
+ if (hasContent(v[k], depth + 1, seen)) return true;
183
+ }
184
+ } catch (e6) {
185
+ }
186
+ return false;
187
+ }
188
+ function normalizeError(value) {
189
+ if (value instanceof Error) return value;
190
+ if (value === null || value === void 0) return null;
191
+ switch (typeof value) {
192
+ case "string":
193
+ return str(value) ? new Error(value) : null;
194
+ case "number":
195
+ case "boolean":
196
+ case "bigint":
197
+ return new Error(String(value));
198
+ case "symbol":
199
+ return new Error(value.toString());
200
+ case "function":
201
+ return null;
202
+ case "object":
203
+ break;
204
+ default:
205
+ return null;
206
+ }
207
+ const o = value;
208
+ if (o.error !== void 0 && o.error !== value) {
209
+ const inner = normalizeError(o.error);
210
+ if (inner) return inner;
211
+ }
212
+ if (o.reason !== void 0 && o.reason !== value) {
213
+ const inner = normalizeError(o.reason);
214
+ if (inner) return inner;
215
+ }
216
+ const message = _nullishCoalesce(_nullishCoalesce(str(o.message), () => ( str(o.description))), () => ( str(o.msg)));
217
+ if (message) return withMeta(new Error(message), o);
218
+ let json;
219
+ try {
220
+ json = hasContent(value) ? JSON.stringify(value) : void 0;
221
+ } catch (e7) {
222
+ json = void 0;
223
+ }
224
+ if (json && json !== "{}" && json !== "[]" && json !== "null") {
225
+ return withMeta(
226
+ new Error(json.length > MAX_JSON_MESSAGE ? `${json.slice(0, MAX_JSON_MESSAGE)}\u2026` : json),
227
+ o
228
+ );
229
+ }
230
+ try {
231
+ const s = String(value);
232
+ if (s && !/^\[object [A-Za-z]+\]$/.test(s) && s !== "{}") {
233
+ return withMeta(new Error(s), o);
234
+ }
235
+ } catch (e8) {
134
236
  }
237
+ return null;
135
238
  }
136
239
 
137
240
  // src/index.ts
@@ -141,7 +244,7 @@ function safeStack(err) {
141
244
  if (err && typeof err === "object" && "stack" in err) {
142
245
  return String(_nullishCoalesce(err.stack, () => ( "")));
143
246
  }
144
- } catch (e3) {
247
+ } catch (e9) {
145
248
  }
146
249
  return void 0;
147
250
  }
@@ -165,7 +268,7 @@ function captureWindowError(event) {
165
268
  url: typeof location !== "undefined" ? location.href : void 0
166
269
  });
167
270
  }
168
- } catch (e4) {
271
+ } catch (e10) {
169
272
  }
170
273
  }
171
274
  function attachListeners() {
@@ -180,6 +283,7 @@ function detachListeners() {
180
283
  }
181
284
  var pendingReplayErrors = [];
182
285
  var replayEnabled = false;
286
+ var replayRequested = false;
183
287
  var replayEpoch = 0;
184
288
  var noopReplay = {
185
289
  _captureError(signal) {
@@ -216,12 +320,25 @@ var Segi = {
216
320
  init(options, opts = {}) {
217
321
  try {
218
322
  const w = typeof window !== "undefined" ? window : null;
323
+ if (!options || options.enabled === false) {
324
+ if (opts.force && state.initialized) Segi.close();
325
+ return;
326
+ }
327
+ const replay = _chunkUSYEDAPQjs.normalizeReplayToken.call(void 0, options.replay);
328
+ const wantsReplay = !!replay && replay.options.enabled !== false;
219
329
  const already = state.initialized || _optionalChain([w, 'optionalAccess', _2 => _2.__segiInitialized]) === true;
220
330
  if (already && !opts.force) {
221
331
  if (!opts.silent && typeof console !== "undefined") {
222
- console.warn(
223
- "[segi] init() called more than once; ignoring. Pass { force: true } to override."
224
- );
332
+ const firstHadReplay = state.initialized ? replayRequested : _optionalChain([w, 'optionalAccess', _3 => _3.__segiReplayRequested]) === true;
333
+ if (wantsReplay && !firstHadReplay) {
334
+ console.warn(
335
+ `[segi] init() was already called WITHOUT session replay (first init wins \u2014 often the CDN auto-init from window.SegiConfig or the script's data-project-key), so the replay option of this call was ignored and nothing is being recorded. Fix: enable replay in that first init (window.SegiConfig = { projectKey, replay: true } or data-replay="true" on the script tag) and drop this call, or call Segi.init({...}, { force: true }) to replace the first init.`
336
+ );
337
+ } else {
338
+ console.warn(
339
+ "[segi] init() called more than once; ignoring. Pass { force: true } to override."
340
+ );
341
+ }
225
342
  }
226
343
  return;
227
344
  }
@@ -230,13 +347,17 @@ var Segi = {
230
347
  Segi.replay = noopReplay;
231
348
  pendingReplayErrors = [];
232
349
  const epoch = ++replayEpoch;
233
- const { replay, ...core } = options;
234
- replayEnabled = !!_optionalChain([replay, 'optionalAccess', _3 => _3.__segi_replay]) && replay.options.enabled !== false;
350
+ const { replay: _ignored, ...core } = options;
351
+ replayEnabled = wantsReplay;
352
+ replayRequested = wantsReplay;
235
353
  state.options = { ...core };
236
354
  state.initialized = true;
237
- if (w) w.__segiInitialized = true;
355
+ if (w) {
356
+ w.__segiInitialized = true;
357
+ w.__segiReplayRequested = wantsReplay;
358
+ }
238
359
  attachListeners();
239
- if (_optionalChain([replay, 'optionalAccess', _4 => _4.__segi_replay])) {
360
+ if (replay && wantsReplay) {
240
361
  void Promise.resolve().then(() => _interopRequireWildcard(require("./replay/index.js"))).then((mod) => {
241
362
  if (epoch !== replayEpoch || !state.initialized) return;
242
363
  Segi.replay = mod.replayApi;
@@ -258,9 +379,17 @@ var Segi = {
258
379
  }).catch(() => {
259
380
  });
260
381
  }
261
- } catch (e5) {
382
+ } catch (e11) {
262
383
  }
263
384
  },
385
+ /**
386
+ * Build the replay activation token for `Segi.init({ replay })`. Same as
387
+ * `withReplay` from `@extn/segi-js/replay`; on the CDN global it defaults
388
+ * `trackRoutes` to true.
389
+ */
390
+ withReplay(options = {}) {
391
+ return _chunkUSYEDAPQjs.withReplay.call(void 0, options);
392
+ },
264
393
  /** True if init() has been called successfully on this bundle. */
265
394
  isInitialized() {
266
395
  return state.initialized;
@@ -271,6 +400,7 @@ var Segi = {
271
400
  detachListeners();
272
401
  replayEpoch++;
273
402
  replayEnabled = false;
403
+ replayRequested = false;
274
404
  Segi.replay._stop();
275
405
  Segi.replay = noopReplay;
276
406
  pendingReplayErrors = [];
@@ -281,14 +411,20 @@ var Segi = {
281
411
  if (typeof window !== "undefined") {
282
412
  const w = window;
283
413
  w.__segiInitialized = false;
414
+ w.__segiReplayRequested = false;
284
415
  }
285
- } catch (e6) {
416
+ } catch (e12) {
286
417
  }
287
418
  },
288
419
  captureException(error, context = {}) {
289
420
  try {
290
421
  if (!state.initialized) return;
291
- const err = error instanceof Error ? error : new Error(typeof error === "string" ? error : JSON.stringify(error));
422
+ let err = normalizeError(error);
423
+ if (!err) {
424
+ const fallback = typeof context.message === "string" ? context.message.trim() : "";
425
+ if (!fallback) return;
426
+ err = new Error(fallback);
427
+ }
292
428
  const evt = buildEvent(state, {
293
429
  type: "error",
294
430
  level: "error",
@@ -309,7 +445,7 @@ var Segi = {
309
445
  Segi.replay._captureError({ ts: evt.timestamp || (/* @__PURE__ */ new Date()).toISOString(), url: evt.url });
310
446
  }
311
447
  send(state.options.endpoint, state.options.projectKey, evt);
312
- } catch (e7) {
448
+ } catch (e13) {
313
449
  }
314
450
  },
315
451
  captureMessage(message, context = {}) {
@@ -333,20 +469,20 @@ var Segi = {
333
469
  Segi.replay._captureError({ ts: evt.timestamp || (/* @__PURE__ */ new Date()).toISOString(), url: evt.url });
334
470
  }
335
471
  send(state.options.endpoint, state.options.projectKey, evt);
336
- } catch (e8) {
472
+ } catch (e14) {
337
473
  }
338
474
  },
339
475
  setUser(user) {
340
476
  try {
341
477
  state.user = user;
342
478
  Segi.replay.setUser(user ? { id: user.id, email: user.email } : null);
343
- } catch (e9) {
479
+ } catch (e15) {
344
480
  }
345
481
  },
346
482
  setTag(key, value) {
347
483
  try {
348
484
  state.tags[key] = value;
349
- } catch (e10) {
485
+ } catch (e16) {
350
486
  }
351
487
  },
352
488
  addBreadcrumb(breadcrumb) {
@@ -355,7 +491,7 @@ var Segi = {
355
491
  ...breadcrumb,
356
492
  timestamp: _nullishCoalesce(breadcrumb.timestamp, () => ( (/* @__PURE__ */ new Date()).toISOString()))
357
493
  });
358
- } catch (e11) {
494
+ } catch (e17) {
359
495
  }
360
496
  }
361
497
  };
@@ -363,4 +499,5 @@ var src_default = Segi;
363
499
 
364
500
 
365
501
 
366
- exports.Segi = Segi; exports.default = src_default;
502
+
503
+ exports.Segi = Segi; exports.default = src_default; exports.normalizeError = normalizeError;