@npaw/forge-web 9.7.5 → 10.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.
Binary file
package/dist/index.cjs CHANGED
@@ -159,6 +159,225 @@ function isCapturePlanEnabled(bits, bit) {
159
159
  return (bits & bit) !== 0;
160
160
  }
161
161
 
162
+ // src/network-timing.ts
163
+ var DEFAULT_MATCH_TOLERANCE_MS = 250;
164
+ var DEFAULT_MATCH_TIMEOUT_MS = 2e3;
165
+ var DEFAULT_MAX_PENDING = 256;
166
+ function phaseMs(end, start) {
167
+ if (!Number.isFinite(end) || !Number.isFinite(start)) {
168
+ return void 0;
169
+ }
170
+ if (start <= 0) {
171
+ return void 0;
172
+ }
173
+ const delta = end - start;
174
+ if (!Number.isFinite(delta) || delta <= 0) {
175
+ return void 0;
176
+ }
177
+ return Math.round(delta);
178
+ }
179
+ function nonNegativeMs(value) {
180
+ if (!Number.isFinite(value) || value < 0) {
181
+ return void 0;
182
+ }
183
+ return Math.round(value);
184
+ }
185
+ function positiveBytes(value) {
186
+ if (!Number.isFinite(value) || value <= 0) {
187
+ return void 0;
188
+ }
189
+ return Math.round(value);
190
+ }
191
+ function timingFieldsFromResourceEntry(entry) {
192
+ var _a, _b;
193
+ const fields = {};
194
+ const duration = nonNegativeMs(entry.duration);
195
+ if (duration !== void 0) {
196
+ fields.durationMs = duration;
197
+ }
198
+ const timeToFirstByteMs = (_a = phaseMs(entry.responseStart, entry.requestStart)) != null ? _a : phaseMs(entry.responseStart, entry.startTime);
199
+ if (timeToFirstByteMs !== void 0) {
200
+ fields.timeToFirstByteMs = timeToFirstByteMs;
201
+ }
202
+ const dnsDurationMs = phaseMs(entry.domainLookupEnd, entry.domainLookupStart);
203
+ if (dnsDurationMs !== void 0) {
204
+ fields.dnsDurationMs = dnsDurationMs;
205
+ }
206
+ const connectDurationMs = phaseMs(entry.connectEnd, entry.connectStart);
207
+ if (connectDurationMs !== void 0) {
208
+ fields.connectDurationMs = connectDurationMs;
209
+ }
210
+ const sslDurationMs = phaseMs(entry.connectEnd, entry.secureConnectionStart);
211
+ if (sslDurationMs !== void 0) {
212
+ fields.sslDurationMs = sslDurationMs;
213
+ }
214
+ const responseDownloadDurationMs = phaseMs(entry.responseEnd, entry.responseStart);
215
+ if (responseDownloadDurationMs !== void 0) {
216
+ fields.responseDownloadDurationMs = responseDownloadDurationMs;
217
+ }
218
+ const redirectDurationMs = phaseMs(entry.redirectEnd, entry.redirectStart);
219
+ if (redirectDurationMs !== void 0) {
220
+ fields.redirectDurationMs = redirectDurationMs;
221
+ fields.redirectCount = 1;
222
+ }
223
+ if (typeof entry.nextHopProtocol === "string" && entry.nextHopProtocol.length > 0) {
224
+ fields.protocol = entry.nextHopProtocol;
225
+ }
226
+ const responseBytes = (_b = positiveBytes(entry.transferSize)) != null ? _b : positiveBytes(entry.encodedBodySize);
227
+ if (responseBytes !== void 0) {
228
+ fields.responseBytes = responseBytes;
229
+ }
230
+ return fields;
231
+ }
232
+ function timingMatchKey(url) {
233
+ var _a, _b;
234
+ const withoutFragment = (_a = url.split("#")[0]) != null ? _a : url;
235
+ return (_b = withoutFragment.split("?")[0]) != null ? _b : withoutFragment;
236
+ }
237
+ var ResourceTimingCorrelator = class {
238
+ constructor(options) {
239
+ this.options = options;
240
+ this.pending = /* @__PURE__ */ new Map();
241
+ this.pendingCount = 0;
242
+ this.disposed = false;
243
+ var _a, _b, _c;
244
+ this.toleranceMs = (_a = options.toleranceMs) != null ? _a : DEFAULT_MATCH_TOLERANCE_MS;
245
+ this.timeoutMs = (_b = options.timeoutMs) != null ? _b : DEFAULT_MATCH_TIMEOUT_MS;
246
+ this.maxPending = (_c = options.maxPending) != null ? _c : DEFAULT_MAX_PENDING;
247
+ try {
248
+ this.observer = options.observerFactory((entries) => this.onEntries(entries));
249
+ } catch (e) {
250
+ this.observer = void 0;
251
+ }
252
+ }
253
+ /** True when correlation is actually available; false means timeout-only. */
254
+ get active() {
255
+ return this.observer !== void 0;
256
+ }
257
+ track(observation, url, startedAtMs) {
258
+ if (this.disposed || !this.observer) {
259
+ this.options.emit(observation);
260
+ return;
261
+ }
262
+ const key = timingMatchKey(url);
263
+ const record = {
264
+ key,
265
+ startedAtMs,
266
+ observation,
267
+ timer: void 0,
268
+ emitted: false
269
+ };
270
+ record.timer = this.options.setTimer(() => this.flush(record, false), this.timeoutMs);
271
+ const bucket = this.pending.get(key);
272
+ if (bucket) {
273
+ bucket.push(record);
274
+ } else {
275
+ this.pending.set(key, [record]);
276
+ }
277
+ this.pendingCount += 1;
278
+ this.evictOverflow();
279
+ }
280
+ dispose() {
281
+ var _a;
282
+ this.disposed = true;
283
+ try {
284
+ (_a = this.observer) == null ? void 0 : _a.disconnect();
285
+ } catch (e) {
286
+ }
287
+ for (const bucket of [...this.pending.values()]) {
288
+ for (const record of [...bucket]) {
289
+ this.flush(record, false);
290
+ }
291
+ }
292
+ this.pending.clear();
293
+ this.pendingCount = 0;
294
+ }
295
+ onEntries(entries) {
296
+ for (const entry of entries) {
297
+ if (!entry || entry.entryType !== "resource") {
298
+ continue;
299
+ }
300
+ const record = this.take(entry);
301
+ if (!record) {
302
+ continue;
303
+ }
304
+ Object.assign(record.observation, timingFieldsFromResourceEntry(entry));
305
+ this.flush(record, true);
306
+ }
307
+ }
308
+ /**
309
+ * Pairs an entry with the closest pending observation for the same URL whose
310
+ * start time falls inside the tolerance window. Matching on start time as
311
+ * well as URL is what keeps concurrent requests to one endpoint apart.
312
+ */
313
+ take(entry) {
314
+ const bucket = this.pending.get(timingMatchKey(entry.name));
315
+ if (!bucket || bucket.length === 0) {
316
+ return void 0;
317
+ }
318
+ let best;
319
+ let bestDistance = Number.POSITIVE_INFINITY;
320
+ for (const record of bucket) {
321
+ if (record.emitted) {
322
+ continue;
323
+ }
324
+ const distance = Math.abs(record.startedAtMs - entry.startTime);
325
+ if (distance < bestDistance) {
326
+ bestDistance = distance;
327
+ best = record;
328
+ }
329
+ }
330
+ return bestDistance > this.toleranceMs ? void 0 : best;
331
+ }
332
+ flush(record, matched) {
333
+ var _a, _b;
334
+ if (record.emitted) {
335
+ return;
336
+ }
337
+ record.emitted = true;
338
+ this.detach(record);
339
+ this.options.clearTimer(record.timer);
340
+ if (!matched) {
341
+ (_b = (_a = this.options).onUnmatched) == null ? void 0 : _b.call(_a, record.observation);
342
+ }
343
+ this.options.emit(record.observation);
344
+ }
345
+ detach(record) {
346
+ const bucket = this.pending.get(record.key);
347
+ if (!bucket) {
348
+ return;
349
+ }
350
+ const index = bucket.indexOf(record);
351
+ if (index >= 0) {
352
+ bucket.splice(index, 1);
353
+ this.pendingCount -= 1;
354
+ }
355
+ if (bucket.length === 0) {
356
+ this.pending.delete(record.key);
357
+ }
358
+ }
359
+ evictOverflow() {
360
+ while (this.pendingCount > this.maxPending) {
361
+ const oldest = this.oldestRecord();
362
+ if (!oldest) {
363
+ return;
364
+ }
365
+ this.flush(oldest, false);
366
+ }
367
+ }
368
+ oldestRecord() {
369
+ let oldest;
370
+ for (const bucket of this.pending.values()) {
371
+ for (const record of bucket) {
372
+ if (!oldest || record.startedAtMs < oldest.startedAtMs) {
373
+ oldest = record;
374
+ }
375
+ }
376
+ }
377
+ return oldest;
378
+ }
379
+ };
380
+
162
381
  // src/sections-capture.ts
163
382
  var DEFAULT_VISIBILITY_THRESHOLD_PCT = 50;
164
383
  var DEFAULT_IMPRESSION_MIN_VISIBLE_MS = 1e3;
@@ -1736,6 +1955,8 @@ var BrowserCapture = class {
1736
1955
  this.featureDisposers = /* @__PURE__ */ new Map();
1737
1956
  this.lastScrollAtMs = 0;
1738
1957
  this.disposed = false;
1958
+ /** Observations emitted on wrapper timing because no entry ever matched. */
1959
+ this.unmatchedNetworkTimings = 0;
1739
1960
  this.initialNavigationReported = false;
1740
1961
  this.attributionReported = false;
1741
1962
  this.foregroundCount = 0;
@@ -2344,6 +2565,7 @@ var BrowserCapture = class {
2344
2565
  sink.push(() => {
2345
2566
  generation.active = false;
2346
2567
  });
2568
+ this.installResourceTimingCorrelator(sink);
2347
2569
  if (this.options.network.fetch) {
2348
2570
  this.patchFetch(sink, generation);
2349
2571
  }
@@ -2351,6 +2573,60 @@ var BrowserCapture = class {
2351
2573
  this.patchXmlHttpRequest(sink, generation);
2352
2574
  }
2353
2575
  }
2576
+ /**
2577
+ * The wrappers cannot see connection phases, protocol, or a duration free of
2578
+ * JS scheduling — and a `fetch` promise resolves at headers, so timing it
2579
+ * yields time-to-first-byte rather than duration. The correlator holds each
2580
+ * observation until its Resource Timing entry arrives and merges the two.
2581
+ */
2582
+ installResourceTimingCorrelator(sink) {
2583
+ const factory = this.resourceTimingObserverFactory();
2584
+ if (!factory) {
2585
+ return;
2586
+ }
2587
+ const correlator = new ResourceTimingCorrelator({
2588
+ emit: (observation) => safeCaptureCall(() => this.host.trackNetworkEvent(observation)),
2589
+ observerFactory: factory,
2590
+ setTimer: (callback, delayMs) => this.timers().setTimeout(callback, delayMs),
2591
+ clearTimer: (handle) => this.timers().clearTimeout(handle),
2592
+ onUnmatched: () => {
2593
+ this.unmatchedNetworkTimings += 1;
2594
+ }
2595
+ });
2596
+ if (!correlator.active) {
2597
+ return;
2598
+ }
2599
+ this.networkTimingCorrelator = correlator;
2600
+ sink.push(() => {
2601
+ this.networkTimingCorrelator = void 0;
2602
+ correlator.dispose();
2603
+ });
2604
+ }
2605
+ /**
2606
+ * Prefers an injected factory (tests, non-browser hosts) and otherwise builds
2607
+ * one over `PerformanceObserver`. An observer is used rather than
2608
+ * `getEntriesByType` because the resource buffer caps at 250 entries by
2609
+ * default: a long-lived SPA silently drops the rest, whereas an observer is
2610
+ * handed every entry once as it is recorded.
2611
+ */
2612
+ resourceTimingObserverFactory() {
2613
+ const injected = this.options.environment.resourceTimingObserverFactory;
2614
+ if (injected) {
2615
+ return injected;
2616
+ }
2617
+ const windowRef = this.window();
2618
+ const ObserverCtor = windowRef == null ? void 0 : windowRef.PerformanceObserver;
2619
+ if (typeof ObserverCtor !== "function") {
2620
+ return void 0;
2621
+ }
2622
+ return (callback) => {
2623
+ const observer = new ObserverCtor((list) => {
2624
+ callback(list.getEntries());
2625
+ });
2626
+ observer.observe({ type: "resource", buffered: true });
2627
+ return observer;
2628
+ };
2629
+ }
2354
2630
  installWebVitalsCapture(sink) {
2355
2631
  const handle = installWebVitalsCapture(this.host, this.options);
2356
2632
  sink.push(() => handle.dispose());
@@ -2631,6 +2907,11 @@ var BrowserCapture = class {
2631
2907
  if (Object.keys(responseHeaders).length > 0) {
2632
2908
  observation.responseHeaders = responseHeaders;
2633
2909
  }
2910
+ const correlator = this.networkTimingCorrelator;
2911
+ if (correlator) {
2912
+ correlator.track(observation, metadata.targetUrl, startedAt.elapsedMs);
2913
+ return;
2914
+ }
2634
2915
  safeCaptureCall(() => this.host.trackNetworkEvent(observation));
2635
2916
  }
2636
2917
  emitRawEvent(name, params = {}, presanitized) {
@@ -3736,6 +4017,9 @@ function requestBody(request) {
3736
4017
  if (request.bodyBytes !== void 0) {
3737
4018
  return new Uint8Array(request.bodyBytes);
3738
4019
  }
4020
+ if (request.bodyText !== void 0) {
4021
+ return request.bodyText;
4022
+ }
3739
4023
  if (request.body !== void 0) {
3740
4024
  return JSON.stringify(request.body);
3741
4025
  }
@@ -3947,6 +4231,8 @@ var ForgeRuntimeBridge = class _ForgeRuntimeBridge {
3947
4231
  return command.timestamp === void 0 ? { ...command, timestamp: timestamp(this.clock) } : command;
3948
4232
  case "sessionEvent":
3949
4233
  return command.timemarkMs === void 0 ? { ...command, timemarkMs: this.nowMs() } : command;
4234
+ case "sessionUpdate":
4235
+ return command.timemarkMs === void 0 ? { ...command, timemarkMs: this.nowMs() } : command;
3950
4236
  case "identityEvent":
3951
4237
  return command.timemarkMs === void 0 ? { ...command, timemarkMs: this.nowMs() } : command;
3952
4238
  case "applicationForeground":
@@ -4058,7 +4344,11 @@ function deviceSampleCollector(options) {
4058
4344
  function runtimeConfig(options) {
4059
4345
  var _a, _b;
4060
4346
  const config = {
4061
- accountCode: options.accountCode
4347
+ accountCode: options.accountCode,
4348
+ // Browsers preflight any request with custom headers; the kernel's
4349
+ // CORS-simple profile keeps Forge's own NQS traffic to one HTTP call
4350
+ // per event (the browser supplies User-Agent and Host itself).
4351
+ corsSimpleTransport: true
4062
4352
  };
4063
4353
  assignOptional(config, "appName", options.appName);
4064
4354
  assignOptional(config, "buildVariant", options.buildVariant);
@@ -4078,6 +4368,7 @@ function runtimeConfig(options) {
4078
4368
  "preSessionEventQueueMaxAgeMs",
4079
4369
  options.preSessionEventQueueMaxAgeMs
4080
4370
  );
4371
+ assignOptional(config, "logoutSessionGuardMs", options.logoutSessionGuardMs);
4081
4372
  assignOptional(config, "logLevel", options.logLevel);
4082
4373
  const autoDeviceIdentity = (_a = options.autoDeviceIdentity) != null ? _a : true;
4083
4374
  assignOptional(
@@ -4953,6 +5244,39 @@ var _NPAWForge = class _NPAWForge {
4953
5244
  const normalizedName = name.trim().startsWith("raw_") ? name.trim() : `raw_${name.trim()}`;
4954
5245
  return this.trackSessionEvent(normalizedName, params);
4955
5246
  }
5247
+ /**
5248
+ * Hot-updates session-level dimensions without restarting the session:
5249
+ * `param1`..`param20` extraparams, `screenName`, or any dimension the NQS
5250
+ * parameter registry marks updatable — new backend dimensions work without
5251
+ * an SDK release. The change reaches NQS on the next session event within
5252
+ * one second, or on an immediate beat after that window; the very next
5253
+ * analytics row shows the new values, and later video views inherit them.
5254
+ *
5255
+ * Identity keys (`username`, `profileId`, `userType`, `anonymousUser`) are
5256
+ * rejected — use the typed identity API (`loginSuccess`,
5257
+ * `profileSelected`, `logout`). Blank values are dropped: NQS never erases
5258
+ * a session value. Requires the account's remote config to enable session
5259
+ * updates; otherwise the update is ignored with a diagnostic.
5260
+ */
5261
+ updateSession(params) {
5262
+ return this.runtime.process({
5263
+ type: "sessionUpdate",
5264
+ params: normalizeParams(params)
5265
+ });
5266
+ }
5267
+ /**
5268
+ * Reports numeric session metrics (account-registered custom metrics).
5269
+ * Values accumulate on the server per the account's registered operation
5270
+ * (sum/min/average/...) and settle on the session close row. Re-sending an
5271
+ * unchanged value is a no-op. Same remote-config gating as
5272
+ * {@link updateSession}.
5273
+ */
5274
+ updateSessionMetrics(metrics) {
5275
+ return this.runtime.process({
5276
+ type: "sessionUpdate",
5277
+ metrics
5278
+ });
5279
+ }
4956
5280
  /**
4957
5281
  * Emits a `raw_search` event. The query text is subject to the kernel-side
4958
5282
  * remote visible-text privacy policy, which can strip it before any payload