@steadphast/connector-nextjs 0.6.0 → 0.7.1

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/dist/server.js CHANGED
@@ -2,8 +2,772 @@
2
2
  import { headers } from "next/headers";
3
3
  import { createElement } from "react";
4
4
 
5
+ // src/behavioral-collector.ts
6
+ function behavioralCollector(sdk, nonce, endpoint, timing, issuedAt, route, notice = false, pathCapture = false, timingRoute = "steadphast-host") {
7
+ let closed = false;
8
+ let started = false;
9
+ let start = 0;
10
+ let startTick = 0;
11
+ let timer;
12
+ const records = [];
13
+ let sampled = 0;
14
+ let actions = 0;
15
+ const dropped = [0, 0, 0, 0, 0, 0];
16
+ let lastSample = Number.NEGATIVE_INFINITY;
17
+ let lastMotion;
18
+ let baseline = false;
19
+ let moved = false;
20
+ let inputObserved = false;
21
+ const motionTimes = [];
22
+ let pointerDown = false;
23
+ let downGeometry;
24
+ let keyDownAt;
25
+ let keyOverlap = false;
26
+ let outstandingKeys = 0;
27
+ let lastKeyUp;
28
+ let keyFlight;
29
+ let lastKeyEvent = Number.NEGATIVE_INFINITY;
30
+ let keyIntervals = 0;
31
+ let scrollIntervals = 0;
32
+ let lastScroll;
33
+ let scrollX = 0;
34
+ let scrollY = 0;
35
+ let lastRawScroll;
36
+ let rawScrollX = 0;
37
+ let rawScrollY = 0;
38
+ let burstFromX = 0;
39
+ let burstFromY = 0;
40
+ let burstEvents = 0;
41
+ const counts = {
42
+ pointer_origin_clicks: 0,
43
+ pointer_origin_clicks_without_motion: 0,
44
+ paste_inputs: 0,
45
+ scroll_bursts: 0,
46
+ single_event_scroll_burst_bins: [0, 0, 0, 0, 0, 0, 0, 0]
47
+ };
48
+ const inputCounts = [0, 0, 0, 0];
49
+ const focused = /* @__PURE__ */ new WeakSet();
50
+ const changed = /* @__PURE__ */ new WeakSet();
51
+ const together = /* @__PURE__ */ new WeakSet();
52
+ let instant = [];
53
+ let lastInput = Number.NEGATIVE_INFINITY;
54
+ const pointerPosition = [0, 0, 0, 0];
55
+ const otherPosition = [0, 0, 0];
56
+ const inputPosition = [0, 0];
57
+ let forwarded;
58
+ let roundTrip;
59
+ let quantum = null;
60
+ let lastClock;
61
+ const listeners = [];
62
+ const encoder = new TextEncoder();
63
+ let recordBytes = 0;
64
+ const budget = 4096 - encoder.encode(
65
+ JSON.stringify({
66
+ version: "1",
67
+ nonce,
68
+ started_at_ms: Date.now(),
69
+ duration_ms: 3e4,
70
+ end: "action-limit",
71
+ timing_enabled: timing,
72
+ timer_quantum_ms: 65535,
73
+ actions: 100,
74
+ sampled: 1024,
75
+ dropped: [65535, 65535, 65535, 65535, 65535, 65535],
76
+ records: [],
77
+ counts: {
78
+ pointer_origin_clicks: 100,
79
+ pointer_origin_clicks_without_motion: 100,
80
+ paste_inputs: 100,
81
+ scroll_bursts: 100,
82
+ single_event_scroll_burst_bins: [
83
+ 100,
84
+ 100,
85
+ 100,
86
+ 100,
87
+ 100,
88
+ 100,
89
+ 100,
90
+ 100
91
+ ],
92
+ pointer_motion_observed: false,
93
+ input_observed: false,
94
+ control_inputs: 1e3,
95
+ control_inputs_without_focus: 1e3,
96
+ changed_controls: 100,
97
+ controls_changed_in_one_instant: 100,
98
+ pointer_click_position: [100, 100, 100, 100],
99
+ other_activation_position: [100, 100, 100],
100
+ input_position: [1e3, 1e3]
101
+ },
102
+ page_round_trip_ms: 3e4
103
+ })
104
+ ).length - 64;
105
+ let observer;
106
+ function listen(target2, name, callback) {
107
+ const fn = callback;
108
+ target2.addEventListener(name, fn, { passive: true, capture: true });
109
+ listeners.push([target2, name, fn]);
110
+ }
111
+ function discard() {
112
+ if (closed) return;
113
+ closed = true;
114
+ clearTimeout(timer);
115
+ clearTimeout(expiry);
116
+ for (const [target2, name, fn] of listeners)
117
+ target2.removeEventListener(name, fn, true);
118
+ listeners.length = 0;
119
+ observer?.disconnect();
120
+ observer = void 0;
121
+ roundTrip?.cancel();
122
+ instant = [];
123
+ forwarded = void 0;
124
+ records.length = 0;
125
+ dropped.length = 0;
126
+ keyDownAt = void 0;
127
+ lastKeyUp = void 0;
128
+ keyFlight = void 0;
129
+ lastMotion = void 0;
130
+ lastClock = void 0;
131
+ lastScroll = void 0;
132
+ lastRawScroll = void 0;
133
+ motionTimes.length = 0;
134
+ downGeometry = void 0;
135
+ }
136
+ function closeBurst() {
137
+ if (burstEvents === 1) {
138
+ const distance = Math.hypot(
139
+ rawScrollX - burstFromX,
140
+ rawScrollY - burstFromY
141
+ );
142
+ let bin = 0;
143
+ for (const edge of [25, 50, 100, 200, 400, 800, 1600])
144
+ if (distance >= edge) bin++;
145
+ const bins = counts.single_event_scroll_burst_bins;
146
+ bins[bin] = (bins[bin] ?? 0) + 1;
147
+ }
148
+ burstEvents = 0;
149
+ }
150
+ function finish(end) {
151
+ if (closed) return;
152
+ if (!started) {
153
+ discard();
154
+ return;
155
+ }
156
+ closeBurst();
157
+ const keys = records.filter(
158
+ (record) => record.kind === "key"
159
+ );
160
+ const canonical = (values) => values.map((value) => value == null ? null : value - value % 10).sort(
161
+ (a, b) => a === null ? b === null ? 0 : -1 : b === null ? 1 : a - b
162
+ );
163
+ const dwell = canonical(keys.map((key) => key.dwell_ms));
164
+ const flight = canonical(keys.map((key) => key.flight_ms));
165
+ keys.forEach((key, index) => {
166
+ key.dwell_ms = dwell[index] ?? null;
167
+ key.flight_ms = flight[index] ?? null;
168
+ });
169
+ const payload = {
170
+ version: "1",
171
+ nonce,
172
+ started_at_ms: start,
173
+ duration_ms: Math.min(
174
+ 3e4,
175
+ Math.max(0, Math.round(performance.now() - startTick))
176
+ ),
177
+ end,
178
+ timing_enabled: timing,
179
+ timer_quantum_ms: timing ? quantum : null,
180
+ actions,
181
+ sampled,
182
+ dropped,
183
+ records,
184
+ counts: {
185
+ ...counts,
186
+ pointer_motion_observed: moved,
187
+ input_observed: inputObserved,
188
+ control_inputs: inputCounts[0],
189
+ control_inputs_without_focus: inputCounts[1],
190
+ changed_controls: inputCounts[2],
191
+ controls_changed_in_one_instant: inputCounts[3],
192
+ pointer_click_position: pointerPosition,
193
+ other_activation_position: otherPosition,
194
+ input_position: inputPosition
195
+ },
196
+ ...roundTrip?.reading.state === "observed" ? { page_round_trip_ms: roundTrip.reading.value } : {}
197
+ };
198
+ const body = JSON.stringify(payload);
199
+ discard();
200
+ if (encoder.encode(body).length > 4096) return;
201
+ void fetch(endpoint, {
202
+ method: "POST",
203
+ body,
204
+ headers: { "content-type": "text/plain" },
205
+ credentials: "omit",
206
+ keepalive: true,
207
+ mode: "cors",
208
+ cache: "no-store"
209
+ }).catch(() => {
210
+ });
211
+ }
212
+ function active() {
213
+ if (!started || closed) return false;
214
+ if (location.pathname !== route) {
215
+ finish("route-change");
216
+ return false;
217
+ }
218
+ if (performance.now() - startTick >= 3e4) {
219
+ finish("deadline");
220
+ return false;
221
+ }
222
+ return true;
223
+ }
224
+ function clock() {
225
+ const now = performance.now();
226
+ if (timing && lastClock !== void 0 && now > lastClock) {
227
+ const delta = Math.ceil(now - lastClock);
228
+ quantum = quantum === null ? delta : Math.min(quantum, delta);
229
+ }
230
+ if (timing) lastClock = now;
231
+ return now;
232
+ }
233
+ function at() {
234
+ return timing ? Math.min(3e4, Math.max(0, Math.round(clock() - startTick))) : null;
235
+ }
236
+ function drop(group) {
237
+ dropped[group] = Math.min(65535, (dropped[group] ?? 0) + 1);
238
+ }
239
+ function add(record, group) {
240
+ if (!active()) return;
241
+ if (sampled >= 1024) {
242
+ drop(group);
243
+ return;
244
+ }
245
+ sampled++;
246
+ const size = encoder.encode(JSON.stringify(record)).length + 1;
247
+ if (recordBytes + size > budget) {
248
+ drop(group);
249
+ return;
250
+ }
251
+ recordBytes += size;
252
+ records.push(record);
253
+ }
254
+ function placement(rect) {
255
+ const sized = rect.width > 0 && rect.height > 0;
256
+ return [
257
+ sized && (rect.right <= 0 || rect.bottom <= 0 || rect.left >= window.innerWidth || rect.top >= window.innerHeight),
258
+ !sized
259
+ ];
260
+ }
261
+ function forwardedClick(event, element) {
262
+ const labelForwarded = !!element && forwarded === element;
263
+ forwarded = void 0;
264
+ const path = event.composedPath();
265
+ const label = path.find(
266
+ (node) => node instanceof HTMLLabelElement
267
+ );
268
+ if (label?.control && label.control !== path[0]) {
269
+ forwarded = label.control;
270
+ setTimeout(() => {
271
+ forwarded = void 0;
272
+ }, 0);
273
+ }
274
+ return labelForwarded;
275
+ }
276
+ function clickPosition(element, rect, e, pressed) {
277
+ const [outside, sizeless] = placement(rect);
278
+ if (!pressed) {
279
+ otherPosition[0]++;
280
+ if (outside) otherPosition[1]++;
281
+ if (sizeless) otherPosition[2]++;
282
+ return;
283
+ }
284
+ const root = element.getRootNode();
285
+ const hit = (root instanceof ShadowRoot ? root : document).elementFromPoint(
286
+ e.clientX,
287
+ e.clientY
288
+ );
289
+ pointerPosition[0]++;
290
+ if (!hit || !element.contains(hit)) pointerPosition[1]++;
291
+ if (outside) pointerPosition[2]++;
292
+ if (sizeless) pointerPosition[3]++;
293
+ }
294
+ function countInput(control) {
295
+ if (inputCounts[0] >= 1e3) return;
296
+ const now = performance.now();
297
+ inputCounts[0]++;
298
+ if (!focused.has(control)) inputCounts[1]++;
299
+ if (!changed.has(control) && inputCounts[2] < 100) {
300
+ changed.add(control);
301
+ inputCounts[2]++;
302
+ }
303
+ if (now - lastInput >= 10) instant = [];
304
+ lastInput = now;
305
+ if (!instant.includes(control) && instant.length < 100)
306
+ instant.push(control);
307
+ if (instant.length > 1) {
308
+ for (const member of instant)
309
+ if (changed.has(member) && !together.has(member)) {
310
+ together.add(member);
311
+ inputCounts[3]++;
312
+ }
313
+ }
314
+ const [outside, sizeless] = placement(control.getBoundingClientRect());
315
+ if (outside) inputPosition[0]++;
316
+ if (sizeless) inputPosition[1]++;
317
+ }
318
+ function bound(value) {
319
+ return Math.max(-1e7, Math.min(1e7, Math.round(value)));
320
+ }
321
+ function probe(finish2, signal) {
322
+ if (typeof PerformanceObserver === "undefined") return finish2();
323
+ let accepted = false;
324
+ let duration;
325
+ const watcher = new PerformanceObserver((list) => {
326
+ for (const entry of list.getEntriesByName(endpoint)) {
327
+ const request = entry;
328
+ if (request.initiatorType !== "fetch") continue;
329
+ if (!closed && request.requestStart > 0 && request.responseStart >= request.requestStart) {
330
+ duration = Math.min(
331
+ 3e4,
332
+ Math.round(request.responseStart - request.requestStart)
333
+ );
334
+ if (accepted) finish2(duration);
335
+ } else finish2();
336
+ return;
337
+ }
338
+ });
339
+ signal.addEventListener("abort", () => watcher.disconnect(), {
340
+ once: true
341
+ });
342
+ watcher.observe({ type: "resource" });
343
+ void fetch(endpoint, {
344
+ method: "GET",
345
+ credentials: "omit",
346
+ mode: "cors",
347
+ cache: "no-store",
348
+ signal,
349
+ redirect: "error"
350
+ }).then(
351
+ (response) => {
352
+ if (!response.ok) return finish2();
353
+ accepted = true;
354
+ if (duration !== void 0) finish2(duration);
355
+ },
356
+ () => finish2()
357
+ );
358
+ }
359
+ function action() {
360
+ if (!closed && ++actions >= 100) finish("action-limit");
361
+ }
362
+ function resetKeys() {
363
+ keyDownAt = void 0;
364
+ keyFlight = void 0;
365
+ lastKeyUp = void 0;
366
+ outstandingKeys = 0;
367
+ keyOverlap = false;
368
+ }
369
+ function settleKeys() {
370
+ if (outstandingKeys > 0 && performance.now() - lastKeyEvent > 2e3)
371
+ resetKeys();
372
+ }
373
+ function refused(node, control) {
374
+ if (node.matches("[data-discover-sensitive], [contenteditable]"))
375
+ return true;
376
+ if (!(node instanceof HTMLInputElement || node instanceof HTMLTextAreaElement || node instanceof HTMLSelectElement))
377
+ return false;
378
+ const autocomplete = node.getAttribute("autocomplete") ?? "";
379
+ const textField = node instanceof HTMLTextAreaElement || node instanceof HTMLInputElement && /^(text|search|email|tel|url)$/.test(node.type);
380
+ return node instanceof HTMLInputElement && !textField && !/^(button|checkbox|radio|range|number|submit|reset)$/.test(
381
+ node.type
382
+ ) || textField && control !== "key" || /password|cc-|payment|transaction|one-time|bday|birth|sex|health/i.test(
383
+ autocomplete
384
+ ) || // A reveal toggle turns a password field into a text field; its name or id still tells.
385
+ // Secret names fail closed: `code` also matches `postal_code`, `pin` also `shipping`.
386
+ /pass|pwd|otp|pin|cvc|cvv|code|card|ccnum|mfa|2fa|ssn|secret|token/i.test(
387
+ `${node.name} ${node.id}`
388
+ ) || // A field that asks for the visitor's details gives key timing only.
389
+ control !== "key" && (/^(email|tel)$/.test(node.type) || /email|tel|name|address|postal-code|country/i.test(autocomplete));
390
+ }
391
+ function target(event, control) {
392
+ const path = event.composedPath();
393
+ const element = path[0];
394
+ if (!(element instanceof HTMLElement) || element.ownerDocument !== document || element instanceof HTMLUnknownElement || element.localName.includes("-") || /^(article|aside|blockquote|body|div|footer|h[1-6]|header|main|nav|p|section|span)$/.test(
395
+ element.localName
396
+ ))
397
+ return void 0;
398
+ let reachesDocument = false;
399
+ for (const node of path) {
400
+ if (node === document) {
401
+ reachesDocument = true;
402
+ break;
403
+ }
404
+ if (node instanceof ShadowRoot) {
405
+ if (node.mode !== "open" || node.ownerDocument !== document)
406
+ return void 0;
407
+ continue;
408
+ }
409
+ if (!(node instanceof HTMLElement) || node.ownerDocument !== document || refused(node, control))
410
+ return void 0;
411
+ }
412
+ if (!reachesDocument) return void 0;
413
+ if (control && (!element.matches('[data-discover-nonsensitive="true"]') || !(element instanceof HTMLSelectElement || element instanceof HTMLButtonElement || element instanceof HTMLInputElement && /^(range|number|checkbox|radio)$/.test(element.type) || control === "key" && (element instanceof HTMLTextAreaElement || element instanceof HTMLInputElement && /^(text|search|email|tel|url)$/.test(element.type)))))
414
+ return void 0;
415
+ return element;
416
+ }
417
+ function motion(event) {
418
+ if (!active()) return;
419
+ const e = event;
420
+ if (e.pointerType !== "mouse" && e.pointerType !== "pen") return;
421
+ const now = performance.now();
422
+ if (!event.composedPath().some((node) => node instanceof HTMLElement && refused(node)))
423
+ moved = true;
424
+ if (timing) {
425
+ lastMotion = now;
426
+ motionTimes.push(now);
427
+ if (motionTimes.length > 3) motionTimes.shift();
428
+ }
429
+ if (!target(event)) return;
430
+ if (now - lastSample < 1e3 / 30) {
431
+ drop(0);
432
+ return;
433
+ }
434
+ lastSample = now;
435
+ baseline = true;
436
+ add(
437
+ {
438
+ kind: "pointer",
439
+ x: Math.round(e.pageX),
440
+ y: Math.round(e.pageY),
441
+ at_ms: at(),
442
+ trusted: e.isTrusted
443
+ },
444
+ 0
445
+ );
446
+ }
447
+ function begin() {
448
+ if (closed || started || document.visibilityState !== "visible" || location.pathname !== route || Date.now() > issuedAt + 6e5)
449
+ return;
450
+ started = true;
451
+ start = Date.now();
452
+ startTick = performance.now();
453
+ scrollX = window.scrollX;
454
+ scrollY = window.scrollY;
455
+ rawScrollX = scrollX;
456
+ rawScrollY = scrollY;
457
+ timer = setTimeout(() => finish("deadline"), 3e4);
458
+ let focusedNow = document.activeElement;
459
+ while (focusedNow) {
460
+ focused.add(focusedNow);
461
+ focusedNow = focusedNow.shadowRoot?.activeElement ?? null;
462
+ }
463
+ if (timing)
464
+ roundTrip = sdk.run(
465
+ "network",
466
+ "page_round_trip_ms",
467
+ timingRoute,
468
+ timing,
469
+ probe
470
+ );
471
+ for (const name of [
472
+ "keydown",
473
+ "pointerdown",
474
+ "touchstart",
475
+ "wheel",
476
+ "beforeinput",
477
+ "input"
478
+ ])
479
+ listen(document, name, (event) => {
480
+ if (event.isTrusted && active()) inputObserved = true;
481
+ });
482
+ listen(document, "pointermove", (event) => {
483
+ const type = event.pointerType;
484
+ if (event.isTrusted && (type === "mouse" || type === "pen") && active())
485
+ inputObserved = true;
486
+ });
487
+ listen(document, "pointermove", motion);
488
+ listen(document, "pointerdown", (event) => {
489
+ const e = event;
490
+ const element = target(event);
491
+ pointerDown = active() && !!element && (e.pointerType === "mouse" || e.pointerType === "pen") && e.isPrimary;
492
+ const rect = pointerDown ? element?.getBoundingClientRect() : void 0;
493
+ downGeometry = rect ? [rect.left, rect.top, rect.width, rect.height] : void 0;
494
+ });
495
+ listen(document, "pointercancel", () => {
496
+ pointerDown = false;
497
+ downGeometry = void 0;
498
+ });
499
+ listen(document, "click", (event) => {
500
+ if (!active()) return;
501
+ const element = target(event);
502
+ const e = event;
503
+ const rect = element?.getBoundingClientRect();
504
+ const geometry = !!rect && !!downGeometry && rect.width > 0 && rect.height > 0 && rect.left === downGeometry[0] && rect.top === downGeometry[1] && rect.width === downGeometry[2] && rect.height === downGeometry[3];
505
+ const origin = pointerDown && e.detail > 0 && geometry;
506
+ const eligible = origin && baseline;
507
+ const pressed = pointerDown && e.detail > 0;
508
+ pointerDown = false;
509
+ downGeometry = void 0;
510
+ const labelForwarded = forwardedClick(event, element);
511
+ if (!element || !rect) return;
512
+ if (origin) {
513
+ counts.pointer_origin_clicks++;
514
+ if (!moved) counts.pointer_origin_clicks_without_motion++;
515
+ }
516
+ if (!labelForwarded) clickPosition(element, rect, e, pressed);
517
+ add(
518
+ {
519
+ kind: "click",
520
+ x: Math.round(e.pageX),
521
+ y: Math.round(e.pageY),
522
+ at_ms: at(),
523
+ trusted: e.isTrusted,
524
+ pointer_eligible: eligible,
525
+ approach_ms: timing && eligible && lastMotion !== void 0 ? Math.min(
526
+ 3e4,
527
+ Math.max(0, Math.round(performance.now() - lastMotion))
528
+ ) : null,
529
+ offset_x: eligible ? Math.round(
530
+ Math.max(
531
+ -1,
532
+ Math.min(1, (e.clientX - rect.left) / rect.width - 0.5)
533
+ ) * 1e3
534
+ ) : null,
535
+ offset_y: eligible ? Math.round(
536
+ Math.max(
537
+ -1,
538
+ Math.min(1, (e.clientY - rect.top) / rect.height - 0.5)
539
+ ) * 1e3
540
+ ) : null,
541
+ // Motion events in the 500 ms before the click, throttled and off-target ones
542
+ // included; 3 means 3 or more.
543
+ approach_samples: timing && eligible ? motionTimes.filter((at2) => performance.now() - at2 <= 500).length : null,
544
+ // Geometry only, page CSS px; no label, selector, text or element identity.
545
+ ...pathCapture ? {
546
+ target_box: {
547
+ x: bound(rect.left + window.scrollX),
548
+ y: bound(rect.top + window.scrollY),
549
+ w: bound(rect.width),
550
+ h: bound(rect.height)
551
+ }
552
+ } : {}
553
+ },
554
+ 0
555
+ );
556
+ action();
557
+ });
558
+ listen(document, "keydown", (event) => {
559
+ if (!active()) return;
560
+ settleKeys();
561
+ lastKeyEvent = performance.now();
562
+ const e = event;
563
+ if (!e.repeat) outstandingKeys = Math.min(101, outstandingKeys + 1);
564
+ if (!target(event, "key") || e.repeat || e.isComposing || e.keyCode === 229 || outstandingKeys > 1) {
565
+ keyDownAt = void 0;
566
+ keyOverlap = true;
567
+ lastKeyUp = void 0;
568
+ return;
569
+ }
570
+ if (keyOverlap) return;
571
+ if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) {
572
+ lastKeyUp = void 0;
573
+ return;
574
+ }
575
+ const now = timing ? clock() : 0;
576
+ keyFlight = timing && lastKeyUp !== void 0 ? Math.min(3e4, Math.max(0, Math.round(now - lastKeyUp))) : void 0;
577
+ keyDownAt = now;
578
+ });
579
+ listen(document, "keyup", (event) => {
580
+ if (!active()) return;
581
+ settleKeys();
582
+ lastKeyEvent = performance.now();
583
+ outstandingKeys = Math.max(0, outstandingKeys - 1);
584
+ if (keyOverlap || outstandingKeys !== 0) {
585
+ if (outstandingKeys === 0) keyOverlap = false;
586
+ keyDownAt = void 0;
587
+ lastKeyUp = void 0;
588
+ return;
589
+ }
590
+ const pressedAt = keyDownAt;
591
+ keyDownAt = void 0;
592
+ const e = event;
593
+ if (pressedAt === void 0 || !target(event, "key") || e.isComposing || e.keyCode === 229) {
594
+ lastKeyUp = void 0;
595
+ return;
596
+ }
597
+ const now = timing ? clock() : 0;
598
+ const duration = timing ? Math.min(3e4, Math.max(0, Math.round(now - pressedAt))) : null;
599
+ const needed = Number(duration !== null) + Number(keyFlight !== void 0);
600
+ if (keyIntervals + needed > 128) {
601
+ drop(1);
602
+ lastKeyUp = void 0;
603
+ keyFlight = void 0;
604
+ action();
605
+ return;
606
+ }
607
+ keyIntervals += needed;
608
+ add(
609
+ {
610
+ kind: "key",
611
+ trusted: event.isTrusted,
612
+ dwell_ms: duration,
613
+ flight_ms: keyFlight ?? null
614
+ },
615
+ 1
616
+ );
617
+ lastKeyUp = timing ? now : void 0;
618
+ keyFlight = void 0;
619
+ action();
620
+ });
621
+ listen(document, "paste", (event) => {
622
+ if (active() && target(event, "input")) {
623
+ add({ kind: "paste", trusted: event.isTrusted }, 2);
624
+ action();
625
+ }
626
+ });
627
+ listen(document, "input", (event) => {
628
+ if (!active()) return;
629
+ const control = target(event, "key");
630
+ if (control) countInput(control);
631
+ if (!target(event, "input")) return;
632
+ const e = event;
633
+ if (e.inputType === "insertFromPaste") {
634
+ counts.paste_inputs = Math.min(100, counts.paste_inputs + 1);
635
+ return;
636
+ }
637
+ settleKeys();
638
+ if (outstandingKeys > 0 || e.isComposing || /Composition/.test(e.inputType))
639
+ return;
640
+ add({ kind: "input", trusted: event.isTrusted }, 2);
641
+ action();
642
+ });
643
+ listen(document, "scroll", (event) => {
644
+ if (!active() || event.target !== document && event.target !== document.documentElement)
645
+ return;
646
+ const now = timing ? clock() : performance.now();
647
+ if (lastRawScroll === void 0 || now - lastRawScroll >= 150) {
648
+ closeBurst();
649
+ counts.scroll_bursts++;
650
+ burstFromX = rawScrollX;
651
+ burstFromY = rawScrollY;
652
+ }
653
+ burstEvents++;
654
+ lastRawScroll = now;
655
+ rawScrollX = window.scrollX;
656
+ rawScrollY = window.scrollY;
657
+ if (lastScroll !== void 0 && now - lastScroll < 150) {
658
+ drop(3);
659
+ return;
660
+ }
661
+ const interval = timing && lastScroll !== void 0 ? Math.min(3e4, Math.max(0, Math.round(now - lastScroll))) : null;
662
+ const dx = Math.round(window.scrollX - scrollX);
663
+ const dy = Math.round(window.scrollY - scrollY);
664
+ scrollX = window.scrollX;
665
+ scrollY = window.scrollY;
666
+ lastScroll = now;
667
+ if (interval !== null && scrollIntervals >= 128) {
668
+ drop(3);
669
+ action();
670
+ return;
671
+ }
672
+ if (interval !== null) scrollIntervals++;
673
+ add(
674
+ {
675
+ kind: "scroll",
676
+ dx,
677
+ dy,
678
+ interval_ms: interval,
679
+ trusted: event.isTrusted
680
+ },
681
+ 3
682
+ );
683
+ action();
684
+ });
685
+ listen(document, "focusin", (event) => {
686
+ if (!active()) return;
687
+ resetKeys();
688
+ const origin = event.composedPath()[0];
689
+ if (origin) focused.add(origin);
690
+ if (target(event)) add({ kind: "focus", trusted: event.isTrusted }, 4);
691
+ });
692
+ listen(window, "blur", resetKeys);
693
+ listen(document, "touchmove", (event) => {
694
+ if (!active() || !target(event)) return;
695
+ const e = event;
696
+ if (e.touches.length !== 1) {
697
+ drop(5);
698
+ return;
699
+ }
700
+ const now = performance.now();
701
+ if (now - lastSample < 1e3 / 30) {
702
+ drop(5);
703
+ return;
704
+ }
705
+ lastSample = now;
706
+ const touch = e.touches[0];
707
+ if (!touch) return;
708
+ add(
709
+ {
710
+ kind: "touch",
711
+ x: Math.round(touch.pageX),
712
+ y: Math.round(touch.pageY),
713
+ at_ms: at(),
714
+ trusted: e.isTrusted,
715
+ pressure: touch.force > 0 && touch.force < 1 && touch.force !== 0.5 ? Math.round(touch.force * 1e3) : null,
716
+ radius_x: touch.radiusX > 1 ? Math.min(1e4, Math.round(touch.radiusX)) : null,
717
+ radius_y: touch.radiusY > 1 ? Math.min(1e4, Math.round(touch.radiusY)) : null
718
+ },
719
+ 5
720
+ );
721
+ });
722
+ listen(document, "touchend", (event) => {
723
+ if (active() && target(event) && event.touches.length === 0)
724
+ action();
725
+ });
726
+ observer = new MutationObserver(() => {
727
+ if (location.pathname !== route) finish("route-change");
728
+ });
729
+ observer.observe(document.documentElement, {
730
+ childList: true,
731
+ subtree: true
732
+ });
733
+ }
734
+ listen(window, "steadphast:behavioral-consent", (event) => {
735
+ const detail = event.detail;
736
+ if (detail?.enabled === false || detail?.revoked === true) {
737
+ discard();
738
+ return;
739
+ }
740
+ if (detail?.granted !== true) {
741
+ if (started) discard();
742
+ return;
743
+ }
744
+ begin();
745
+ });
746
+ listen(window, "steadphast:behavioral-disable", discard);
747
+ listen(window, "steadphast:behavioral-route", () => finish("route-change"));
748
+ listen(window, "popstate", () => finish("route-change"));
749
+ listen(document, "visibilitychange", () => {
750
+ if (document.visibilityState === "hidden") finish("hidden");
751
+ });
752
+ listen(window, "pagehide", () => finish("pagehide"));
753
+ listen(window, "pageshow", (event) => {
754
+ if (event.persisted) discard();
755
+ });
756
+ const expiry = setTimeout(
757
+ discard,
758
+ Math.max(0, issuedAt + 6e5 - Date.now())
759
+ );
760
+ if (notice) {
761
+ listen(document, "visibilitychange", () => {
762
+ if (document.visibilityState === "visible") begin();
763
+ });
764
+ begin();
765
+ }
766
+ window.dispatchEvent(new Event("steadphast:behavioral-ready"));
767
+ }
768
+
5
769
  // src/collector/bundle.ts
6
- var COLLECTOR_SOURCE = `(function(G,ce){var ue=2e3,le=1500,fe=250,de=500,pe=Date.now(),me=typeof performance<"u"?performance.now():0;function J(e,n){var a=typeof globalThis<"u"?globalThis:self,o=a.navigator,i={},v=[],t=null,L=!1,_=/^function (?:get |set )?[\\w$]*\\(\\) \\{\\s*\\[native code\\]\\s*\\}$/;function u(s,c){try{return s()}catch{return c}}function w(){L||(L=!0,clearTimeout(t),n(i))}function d(s,c){if(typeof c=="function"){var l=Function.prototype.toString,p=!1,A,k,U=!1,P=!1;try{_.test(l.call(c))||(p=!0),A=Reflect.ownKeys(c),(A.length!==2||A.indexOf("length")===-1||A.indexOf("name")===-1)&&(p=!0),k=Object.getOwnPropertyDescriptor(c,"name"),(!k||k.writable!==!1)&&(p=!0);try{new c}catch(h){U=h instanceof TypeError}U||(p=!0);try{Object.setPrototypeOf(c,c)}catch{P=!0}P||(p=!0,Object.setPrototypeOf(c,Function.prototype))}catch{p=!0}p&&v.push(s)}}function Oe(s,c){var l=s?Object.getOwnPropertyDescriptor(s.prototype,c):void 0;return l?l.get:void 0}function j(s,c){return s?s.prototype[c]:void 0}i.ua=u(()=>String(o.userAgent)),i.platform=u(()=>String(o.platform)),i.languages=u(()=>Array.prototype.slice.call(o.languages,0,8).map(String)),i.tz=u(()=>Intl.DateTimeFormat().resolvedOptions().timeZone),i.cores=u(()=>o.hardwareConcurrency),i.memory=u(()=>o.deviceMemory),i.brands=u(()=>o.userAgentData.brands.map(s=>s.brand+" "+s.version)),i.webdriver=u(()=>o.webdriver),i.webdriver_own=u(()=>Object.prototype.hasOwnProperty.call(o,"webdriver")),i.headless_ua=u(()=>/HeadlessChrome|PhantomJS|SlimerJS/.test(o.userAgent)),i.clock={date_native:u(()=>_.test(Function.prototype.toString.call(Date.now))),perf_native:u(()=>_.test(Function.prototype.toString.call(a.performance.now)))},i.webgl=u(()=>{var s=e==="worker"?new OffscreenCanvas(8,8):a.document.createElement("canvas"),c=s.getContext("webgl")||s.getContext("webgl2");if(!c)return{ctx:!1};var l=c.getExtension("WEBGL_debug_renderer_info");return{vendor:l?c.getParameter(l.UNMASKED_VENDOR_WEBGL):void 0,renderer:l?c.getParameter(l.UNMASKED_RENDERER_WEBGL):void 0,ctx:!0}},{ctx:!1});var xe=e==="worker"?a.WorkerNavigator:a.Navigator;d("Function.prototype.toString",Function.prototype.toString),d("Date.now",Date.now),d("performance.now",a.performance&&a.performance.now),["webdriver","plugins","languages","hardwareConcurrency","deviceMemory","platform","userAgent"].forEach(s=>{d((e==="worker"?"WorkerNavigator.":"Navigator.")+s+"#get",Oe(xe,s))}),e!=="worker"&&(d("WebGLRenderingContext.getParameter",j(a.WebGLRenderingContext,"getParameter")),d("Permissions.query",j(a.Permissions,"query")),d("HTMLCanvasElement.toDataURL",j(a.HTMLCanvasElement,"toDataURL")),d("CanvasRenderingContext2D.getImageData",j(a.CanvasRenderingContext2D,"getImageData"))),e!=="worker"&&(i.plugins=u(()=>o.plugins.length),i.screen=u(()=>({w:a.screen.width,h:a.screen.height,dpr:a.devicePixelRatio,outer_zero:a.outerWidth===0||a.outerHeight===0}))),e==="main"&&(i.chrome=u(()=>typeof a.chrome=="object"&&a.chrome!==null),i.rtt=u(()=>o.connection.rtt),i.pdf_viewer=u(()=>o.pdfViewerEnabled),i.share=u(()=>typeof o.share=="function"),i.feature_major=Ce(a),i.os_fonts=u(()=>De(a.document))),i.proto=v;var B=u(()=>o.userAgentData.getHighEntropyValues(["architecture","bitness","platformVersion","fullVersionList"]));return B&&typeof B.then=="function"?(t=setTimeout(w,300),B.then(s=>{i.uach={arch:s.architecture,bitness:s.bitness,platform_version:s.platformVersion,full_version_list:(s.fullVersionList||[]).map(c=>c.brand+" "+c.version)},w()},()=>{w()})):w(),()=>{L=!0,clearTimeout(t)};function Ce(s){for(var c=[[141,()=>typeof Math.sumPrecise=="function"],[140,()=>typeof Uint8Array.fromBase64=="function"],[136,()=>typeof RegExp.escape=="function"],[135,()=>typeof s.Float16Array=="function"],[134,()=>typeof Error.isError=="function"],[128,()=>typeof Promise.try=="function"],[126,()=>typeof URL.parse=="function"],[122,()=>typeof Set.prototype.union=="function"],[122,()=>typeof s.Iterator=="function"&&typeof s.Iterator.prototype.map=="function"],[121,()=>typeof Array.fromAsync=="function"],[120,()=>typeof URL.canParse=="function"],[119,()=>typeof Promise.withResolvers=="function"],[117,()=>typeof Object.groupBy=="function"],[110,()=>typeof Array.prototype.toSorted=="function"],[98,()=>typeof s.structuredClone=="function"]],l=0;l<c.length;l+=1)if(u(c[l][1],!1))return c[l][0];return 0}function De(s){var c={mac:["Helvetica Neue","Menlo","Monaco","Apple Color Emoji","SF Pro","Geneva","Avenir"],win:["Segoe UI","Calibri","Consolas","Tahoma","Cambria","Candara"],linux:["DejaVu Sans","Liberation Sans","Ubuntu","Noto Sans","Cantarell","Liberation Mono"]},l=s.createElement("canvas"),p=l.getContext("2d"),A="mmmmmmmmmmlli WAVE 0123 @#%",k=["monospace","sans-serif","serif"],U=k.map(h=>(p.font="24px "+h,p.measureText(A).width)),P={};return Object.keys(c).forEach(h=>{var se=0;c[h].forEach(Re=>{var Le=k.some((Pe,Me)=>(p.font="24px '"+Re+"', "+Pe,p.measureText(A).width!==U[Me]));Le&&(se+=1)}),P[h]=se}),P}}var r={v:1,nonce:G,t:{}},y=null,O=null,x=null,z=!1,C=!1,g=!1,H=!1,K=0,q=0,Z=0,$=!1,D=null,b=null,M=null,f=null,W=null,Y=[],Q=[],F=null,X,ee=m(()=>document.currentScript.nonce,""),te=/^[A-Za-z0-9+/_-]+={0,2}$/.test(ee)?ee:G,ve=document.scripts.length,ge=document.styleSheets.length,re=m(()=>Object.getOwnPropertyNames(window),[]);function m(e,n){try{return e()}catch{return n}}function N(e,n){Y.push(setTimeout(()=>{g||e()},n))}function S(e,n,a,o){e.addEventListener(n,a,o),Q.push([e,n,a,o])}function we(){Y.forEach(clearTimeout),Q.forEach(e=>{e[0].removeEventListener(e[1],e[2],e[3])}),F!==null&&m(()=>cancelAnimationFrame(F)),D&&D.disconnect(),W&&W(),b&&b.terminate(),M&&URL.revokeObjectURL(M),f&&f.parentNode&&f.parentNode.removeChild(f)}var he=/pptr:|__puppeteer_evaluation_script__|__pyppeteer_evaluation_script__|puppeteer-extra|playwright|__playwright_utility_world__|utility|selenium|webdriver/i,ye=/cdc_|selenium|webdriver|__nightmare|callPhantom|domAutomationController|__pw|__playwright|_phantom|__fxdriver|__driver|__lastWatirAlert|__webdriver_script|puppeteer|_Selenium_IDE_Recorder/i,V=[];function T(e){var n=m(()=>String(new Error().stack||""),"");he.test(n)&&V.indexOf(e)===-1&&V.push(e)}T("sync"),m(()=>{var e={};Object.defineProperty(e,"marker",{get:()=>(T("getter"),0)}),e.marker}),N(()=>{T("timeout")},0),m(()=>{F=requestAnimationFrame(()=>{T("raf")})}),m(()=>{var e=new Proxy({},{ownKeys:()=>(K+=1,[])});console.debug(e)}),m(()=>{D=new MutationObserver(e=>{q+=e.length}),D.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0}),N(()=>{D.disconnect()},de)}),S(window,"click",e=>{e.isTrusted===!1&&(Z+=1)},!0),["keydown","pointerdown","mousedown","touchstart","input"].forEach(e=>{S(window,e,n=>{n.isTrusted&&($=!0)},!0)}),W=J("main",e=>{g||(y=e,E())});var ne="("+J.toString()+")";if(typeof Worker!="function"||typeof Blob!="function"||typeof URL.createObjectURL!="function")z=!0;else try{var be="var s=Date.now()-"+Date.now()+";"+ne+'("worker",function(r){r.started=s;r.clock_delta=Date.now();postMessage(r)})';M=URL.createObjectURL(new Blob([be],{type:"text/javascript"})),b=new Worker(M),b.onmessage=e=>{if(!g){var n=e.data;n.clock_delta-=Date.now(),n.started=Math.max(0,n.started),O=n,b.terminate(),E()}},b.onerror=()=>{g||(C=!0,b.terminate(),E())}}catch{C=!0}try{f=document.createElement("iframe"),f.setAttribute("sandbox","allow-scripts"),f.style.display="none",f.setAttribute("aria-hidden","true");var _e='var b=document.createElement("script");b.text="window.__sp_t0_csp=1";document.head.appendChild(b);var bypass=window.__sp_t0_csp===1;delete window.__sp_t0_csp;b.parentNode.removeChild(b);'+ne+'("iframe",function(r){r.clock_delta=Date.now();parent.postMessage({__sp_t0:r,csp_bypass:bypass},"*")})';f.srcdoc=\`<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-\`+te+\`'"><script nonce="\`+te+'">'+_e+"<\\/script>",S(window,"message",e=>{if(!(g||e.source!==f.contentWindow||!e.data||!e.data.__sp_t0)){var n=e.data.__sp_t0;n.clock_delta-=Date.now(),x=n,typeof e.data.csp_bypass=="boolean"&&(X=e.data.csp_bypass),E()}}),f.onerror=()=>{g||(C=!0,E())},(document.body||document.documentElement).appendChild(f)}catch{C=!0}function ae(){H=!0,N(R,fe),E()}document.readyState==="loading"?S(window,"DOMContentLoaded",ae):ae(),N(R,le),S(window,"pagehide",()=>R("early-exit"));function oe(){document.visibilityState==="hidden"&&R("background-tab")}S(document,"visibilitychange",oe),oe();function E(){H&&y&&O&&x&&R()}function Ae(e,n,a){var o=[];if(!e)return o;function i(t,L,_){t&&Object.keys(_).forEach(u=>{var w=_[u](e),d=_[u](t);w!=null&&d!==void 0&&d!==null&&JSON.stringify(w)!==JSON.stringify(d)&&o.push(L+u)})}var v={platform:t=>t.platform,languages:t=>t.languages,hardwareConcurrency:t=>t.cores,deviceMemory:t=>t.memory,brands:t=>t.brands};return i(n,"A7.",v),i(n,"",{"A10.vendor":t=>t.webgl&&t.webgl.vendor,"A10.renderer":t=>t.webgl&&t.webgl.renderer,"A3w.userAgent":t=>t.ua,"A29w.timeZone":t=>t.tz,"A4w.architecture":t=>t.uach&&t.uach.arch,"A4w.bitness":t=>t.uach&&t.uach.bitness,"A4w.platformVersion":t=>t.uach&&t.uach.platform_version,"A4w.fullVersionList":t=>t.uach&&t.uach.full_version_list}),i(a,"A8.",v),i(a,"",{"A8.userAgent":t=>t.ua,"A8.webdriver":t=>t.webdriver,"A8.timeZone":t=>t.tz,"A8.plugins":t=>t.plugins,"A8.dpr":t=>t.screen&&t.screen.dpr,"A8.screenW":t=>t.screen&&t.screen.w,"A8.renderer":t=>t.webgl&&t.webgl.renderer}),o}function ie(e){return!e||!y||["ua","uach","webgl"].forEach(n=>{JSON.stringify(e[n])===JSON.stringify(y[n])&&delete e[n]}),e}function I(e){if(e){var n=e.proto;return delete e.proto,n}}function Se(){var e=m(()=>{var v=Object.getOwnPropertyNames(window);return v.filter(t=>re.indexOf(t)===-1)},[]),n=m(()=>re.concat(e,Object.getOwnPropertyNames(document)).filter(v=>ye.test(v)),[]),a=I(y),o=I(O),i=I(x);r.t.exec=Math.max(0,Math.round(me)),r.t.sent=Math.max(0,Date.now()-pe),r.main=y||void 0,r.worker=ie(O)||void 0,r.iframe=ie(x)||void 0,r.proto={main:a||[],worker:o,iframe:i},r.globals={late:e.slice(0,32),automation:n.slice(0,16)},r.markers={stack:V,console_trap:K,csp_bypass:X},r.dom={mutations_500:q,sheets_added:Math.max(0,document.styleSheets.length-ge),scripts_added:Math.max(0,document.scripts.length-ve)},r.events={untrusted_clicks:Z,any_input:$}}function Ee(e){for(var n=0,a=0;a<e.length;a+=1){var o=e.charCodeAt(a);o<128?n+=1:o<2048?n+=2:o>=55296&&o<=56319?(n+=4,a+=1):n+=3}return n}function ke(){function e(){return r.xrealm=Ae(r.main,r.worker,r.iframe),JSON.stringify(r)}for(var n=e(),a=[()=>{r.globals.late=r.globals.late.slice(0,8)},()=>{r.iframe&&delete r.iframe.uach},()=>{r.worker&&delete r.worker.uach},()=>{r.main&&r.main.uach&&delete r.main.uach.full_version_list},()=>{r.iframe&&delete r.iframe.webgl},()=>{r.worker&&delete r.worker.webgl},()=>{r.iframe&&delete r.iframe.ua},()=>{r.worker&&delete r.worker.ua},()=>{r.proto.main=r.proto.main.slice(0,4)},()=>{delete r.iframe},()=>{delete r.worker},()=>{r.main&&delete r.main.webgl},()=>{r.main&&delete r.main.ua},()=>{delete r.globals},()=>{delete r.main},()=>{delete r.proto}],o=0;o<a.length&&Ee(n)>ue;o+=1)a[o](),r.availability==="available"&&(r.availability="insufficient-observation"),n=e();return n}function R(e){if(!g){g=!0,r.availability=e||(document.visibilityState==="hidden"?"background-tab":z?"unsupported-api":C?"script-failure":y&&O&&x?"available":"insufficient-observation"),we(),Se();var n=ke();m(()=>{fetch(ce,{method:"POST",body:n,keepalive:!0,credentials:"omit",headers:{"content-type":"text/plain"}}).catch(()=>{})})}}})`;
770
+ var COLLECTOR_SOURCE = `(function(be,$,ye,G,_e){var J=2e3,Ae=1500,Se=250,Oe=500,Ee=Date.now(),ke=typeof performance<"u"?performance.now():0;function Y(e,t,l){var a=typeof globalThis<"u"?globalThis:self,c=a.navigator,o={},r=[],E=null,g=!1,m=/^function (?:get |set )?[\\w$]*\\(\\) \\{\\s*\\[native code\\]\\s*\\}$/;function u(i,s){try{return i()}catch{return s}}function b(){g||(g=!0,clearTimeout(E),t(o))}function y(i,s){if(typeof s=="function"){var f=Function.prototype.toString,h=!1,_,M,j=!1,U=!1;try{m.test(f.call(s))||(h=!0),_=Reflect.ownKeys(s),(_.length!==2||_.indexOf("length")===-1||_.indexOf("name")===-1)&&(h=!0),M=Object.getOwnPropertyDescriptor(s,"name"),(!M||M.writable!==!1)&&(h=!0);try{new s}catch(C){j=C instanceof TypeError}j||(h=!0);try{Object.setPrototypeOf(s,s)}catch{U=!0}U||(h=!0,Object.setPrototypeOf(s,Function.prototype))}catch{h=!0}h&&r.push(i)}}function Fe(i,s){var f=i?Object.getOwnPropertyDescriptor(i.prototype,s):void 0;return f?f.get:void 0}function I(i,s){return i?i.prototype[s]:void 0}o.ua=u(()=>String(c.userAgent)),o.platform=u(()=>String(c.platform)),o.languages=u(()=>Array.prototype.slice.call(c.languages,0,8).map(String)),o.tz=u(()=>Intl.DateTimeFormat().resolvedOptions().timeZone),o.cores=u(()=>c.hardwareConcurrency),o.memory=u(()=>c.deviceMemory),o.brands=u(()=>c.userAgentData.brands.map(i=>i.brand+" "+i.version)),o.webdriver=u(()=>c.webdriver),o.webdriver_own=u(()=>Object.prototype.hasOwnProperty.call(c,"webdriver")),o.headless_ua=u(()=>/HeadlessChrome|PhantomJS|SlimerJS/.test(c.userAgent)),o.clock={date_native:u(()=>m.test(Function.prototype.toString.call(Date.now))),perf_native:u(()=>m.test(Function.prototype.toString.call(a.performance.now)))},o.webgl=u(()=>{var i=e==="worker"?new OffscreenCanvas(8,8):a.document.createElement("canvas"),s=i.getContext("webgl")||i.getContext("webgl2");if(!s)return{ctx:!1};var f=s.getExtension("WEBGL_debug_renderer_info");return{vendor:f?s.getParameter(f.UNMASKED_VENDOR_WEBGL):void 0,renderer:f?s.getParameter(f.UNMASKED_RENDERER_WEBGL):void 0,ctx:!0}},{ctx:!1});var We=e==="worker"?a.WorkerNavigator:a.Navigator;y("Function.prototype.toString",Function.prototype.toString),y("Date.now",Date.now),y("performance.now",a.performance&&a.performance.now),["webdriver","plugins","languages","hardwareConcurrency","deviceMemory","platform","userAgent"].forEach(i=>{y((e==="worker"?"WorkerNavigator.":"Navigator.")+i+"#get",Fe(We,i))}),e!=="worker"&&(y("WebGLRenderingContext.getParameter",I(a.WebGLRenderingContext,"getParameter")),y("Permissions.query",I(a.Permissions,"query")),y("HTMLCanvasElement.toDataURL",I(a.HTMLCanvasElement,"toDataURL")),y("CanvasRenderingContext2D.getImageData",I(a.CanvasRenderingContext2D,"getImageData"))),e!=="worker"&&(o.plugins=u(()=>c.plugins.length),o.screen=u(()=>({w:a.screen.width,h:a.screen.height,dpr:a.devicePixelRatio,outer_zero:a.outerWidth===0||a.outerHeight===0}))),e==="main"&&(o.chrome=u(()=>typeof a.chrome=="object"&&a.chrome!==null),o.rtt=u(()=>c.connection.rtt),o.pdf_viewer=u(()=>c.pdfViewerEnabled),o.share=u(()=>typeof c.share=="function"),o.feature_major=Ve(a),o.os_fonts=u(()=>l?l(i=>me(a.document,i)):me(a.document))),o.proto=r;var Z=u(()=>c.userAgentData.getHighEntropyValues(["architecture","bitness","platformVersion","fullVersionList"]));return Z&&typeof Z.then=="function"?(E=setTimeout(b,300),Z.then(i=>{o.uach={arch:i.architecture,bitness:i.bitness,platform_version:i.platformVersion,full_version_list:(i.fullVersionList||[]).map(s=>s.brand+" "+s.version)},b()},()=>{b()})):b(),()=>{g=!0,clearTimeout(E)};function Ve(i){for(var s=[[141,()=>typeof Math.sumPrecise=="function"],[140,()=>typeof Uint8Array.fromBase64=="function"],[136,()=>typeof RegExp.escape=="function"],[135,()=>typeof i.Float16Array=="function"],[134,()=>typeof Error.isError=="function"],[128,()=>typeof Promise.try=="function"],[126,()=>typeof URL.parse=="function"],[122,()=>typeof Set.prototype.union=="function"],[122,()=>typeof i.Iterator=="function"&&typeof i.Iterator.prototype.map=="function"],[121,()=>typeof Array.fromAsync=="function"],[120,()=>typeof URL.canParse=="function"],[119,()=>typeof Promise.withResolvers=="function"],[117,()=>typeof Object.groupBy=="function"],[110,()=>typeof Array.prototype.toSorted=="function"],[98,()=>typeof i.structuredClone=="function"]],f=0;f<s.length;f+=1)if(u(s[f][1],!1))return s[f][0];return 0}function me(i,s){var f={mac:["Helvetica Neue","Menlo","Monaco","Apple Color Emoji","SF Pro","Geneva","Avenir"],win:["Segoe UI","Calibri","Consolas","Tahoma","Cambria","Candara"],linux:["DejaVu Sans","Liberation Sans","Ubuntu","Noto Sans","Cantarell","Liberation Mono"]},h=i.createElement("canvas"),_=h.getContext("2d"),M="mmmmmmmmmmlli WAVE 0123 @#%",j=["monospace","sans-serif","serif"],U=!0;function C(){var A=_.measureText(M).width;return(!Number.isFinite(A)||A<=0)&&(U=!1),A}var Ie=j.map(A=>(_.font="24px "+A,C())),ve={},ge=1,he=0;return Object.keys(f).forEach(A=>{var we=0;f[A].forEach(Ge=>{var Je=j.some((Be,ze)=>(_.font="24px '"+Ge+"', "+Be,C()!==Ie[ze]));Je&&(we+=1,s&&(he|=ge)),s&&(ge<<=1)}),ve[A]=we}),s&&s(U?he:void 0),ve}}var n={v:1,nonce:$,t:{}},D,S=null,P=null,L=null,Q=!1,R=!1,w=!1,X=!1,ee=0,re=0,te=0,ne=!1,N=null,O=null,F=null,d=null,B=null,ae=[],oe=[],z=null,ie,se=p(()=>document.currentScript.nonce,""),ue=/^[A-Za-z0-9+/_-]+={0,2}$/.test(se)?se:$,xe=document.scripts.length,Ce=document.styleSheets.length,ce=p(()=>Object.getOwnPropertyNames(window),[]);function p(e,t){try{return e()}catch{return t}}function W(e,t){ae.push(setTimeout(()=>{w||e()},t))}function k(e,t,l,a){e.addEventListener(t,l,a),oe.push([e,t,l,a])}function De(){ae.forEach(clearTimeout),oe.forEach(e=>{e[0].removeEventListener(e[1],e[2],e[3])}),z!==null&&p(()=>cancelAnimationFrame(z)),N&&N.disconnect(),B&&B(),O&&O.terminate(),F&&URL.revokeObjectURL(F),d&&d.parentNode&&d.parentNode.removeChild(d)}var Pe=/pptr:|__puppeteer_evaluation_script__|__pyppeteer_evaluation_script__|puppeteer-extra|playwright|__playwright_utility_world__|utility|selenium|webdriver/i,Le=/cdc_|selenium|webdriver|__nightmare|callPhantom|domAutomationController|__pw|__playwright|_phantom|__fxdriver|__driver|__lastWatirAlert|__webdriver_script|puppeteer|_Selenium_IDE_Recorder/i,H=[];function V(e){var t=p(()=>String(new Error().stack||""),"");Pe.test(t)&&H.indexOf(e)===-1&&H.push(e)}V("sync"),p(()=>{var e={};Object.defineProperty(e,"marker",{get:()=>(V("getter"),0)}),e.marker}),W(()=>{V("timeout")},0),p(()=>{z=requestAnimationFrame(()=>{V("raf")})}),p(()=>{var e=new Proxy({},{ownKeys:()=>(ee+=1,[])});console.debug(e)}),p(()=>{N=new MutationObserver(e=>{re+=e.length}),N.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0}),W(()=>{N.disconnect()},Oe)}),k(window,"click",e=>{e.isTrusted===!1&&(te+=1)},!0),["keydown","pointerdown","mousedown","touchstart","input"].forEach(e=>{k(window,e,t=>{t.isTrusted&&(ne=!0)},!0)}),B=Y("main",e=>{w||(S=e,x())},G?e=>{var t,l=!1;return D=be.run("environment","fonts","page",!0,a=>{l=!0,t=e(a)}),l?t:(D.cancel(),e())}:void 0);var le="("+Y.toString()+")";if(typeof Worker!="function"||typeof Blob!="function"||typeof URL.createObjectURL!="function")Q=!0;else try{var Re="var s=Date.now()-"+Date.now()+";"+le+'("worker",function(r){r.started=s;r.clock_delta=Date.now();postMessage(r)})';F=URL.createObjectURL(new Blob([Re],{type:"text/javascript"})),O=new Worker(F),O.onmessage=e=>{if(!w){var t=e.data;t.clock_delta-=Date.now(),t.started=Math.max(0,t.started),P=t,O.terminate(),x()}},O.onerror=()=>{w||(R=!0,O.terminate(),x())}}catch{R=!0}try{d=document.createElement("iframe"),d.setAttribute("sandbox","allow-scripts"),d.style.display="none",d.setAttribute("aria-hidden","true");var Ne='var b=document.createElement("script");b.text="window.__sp_t0_csp=1";document.head.appendChild(b);var bypass=window.__sp_t0_csp===1;delete window.__sp_t0_csp;b.parentNode.removeChild(b);'+le+'("iframe",function(r){r.clock_delta=Date.now();parent.postMessage({__sp_t0:r,csp_bypass:bypass},"*")})';d.srcdoc=\`<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-\`+ue+\`'"><script nonce="\`+ue+'">'+Ne+"<\\/script>",k(window,"message",e=>{if(!(w||e.source!==d.contentWindow||!e.data||!e.data.__sp_t0)){var t=e.data.__sp_t0;t.clock_delta-=Date.now(),L=t,typeof e.data.csp_bypass=="boolean"&&(ie=e.data.csp_bypass),x()}}),d.onerror=()=>{w||(R=!0,x())},(document.body||document.documentElement).appendChild(d)}catch{R=!0}function fe(){X=!0,W(T,Se),x()}document.readyState==="loading"?k(window,"DOMContentLoaded",fe):fe(),W(T,Ae),k(window,"pagehide",()=>T("early-exit"));function de(){document.visibilityState==="hidden"&&T("background-tab")}k(document,"visibilitychange",de),de();function x(){X&&S&&P&&L&&T()}function Te(e,t,l){var a=[];if(!e)return a;function c(r,E,g){r&&Object.keys(g).forEach(m=>{var u=g[m](e),b=g[m](r);u!=null&&b!==void 0&&b!==null&&JSON.stringify(u)!==JSON.stringify(b)&&a.push(E+m)})}var o={platform:r=>r.platform,languages:r=>r.languages,hardwareConcurrency:r=>r.cores,deviceMemory:r=>r.memory,brands:r=>r.brands};return c(t,"A7.",o),c(t,"",{"A10.vendor":r=>r.webgl&&r.webgl.vendor,"A10.renderer":r=>r.webgl&&r.webgl.renderer,"A3w.userAgent":r=>r.ua,"A29w.timeZone":r=>r.tz,"A4w.architecture":r=>r.uach&&r.uach.arch,"A4w.bitness":r=>r.uach&&r.uach.bitness,"A4w.platformVersion":r=>r.uach&&r.uach.platform_version,"A4w.fullVersionList":r=>r.uach&&r.uach.full_version_list}),c(l,"A8.",o),c(l,"",{"A8.userAgent":r=>r.ua,"A8.webdriver":r=>r.webdriver,"A8.timeZone":r=>r.tz,"A8.plugins":r=>r.plugins,"A8.dpr":r=>r.screen&&r.screen.dpr,"A8.screenW":r=>r.screen&&r.screen.w,"A8.renderer":r=>r.webgl&&r.webgl.renderer}),a}function pe(e){return!e||!S||["ua","uach","webgl"].forEach(t=>{JSON.stringify(e[t])===JSON.stringify(S[t])&&delete e[t]}),e}function K(e){if(e){var t=e.proto;return delete e.proto,t}}function Me(){var e=p(()=>{var o=Object.getOwnPropertyNames(window);return o.filter(r=>ce.indexOf(r)===-1)},[]),t=p(()=>ce.concat(e,Object.getOwnPropertyNames(document)).filter(o=>Le.test(o)),[]),l=K(S),a=K(P),c=K(L);n.t.exec=Math.max(0,Math.round(ke)),n.t.sent=Math.max(0,Date.now()-Ee),n.main=S||void 0,n.worker=pe(P)||void 0,n.iframe=pe(L)||void 0,je(),n.proto={main:l||[],worker:a,iframe:c},n.globals={late:e.slice(0,32),automation:t.slice(0,16)},n.markers={stack:H,console_trap:ee,csp_bypass:ie},n.dom={mutations_500:re,sheets_added:Math.max(0,document.styleSheets.length-Ce),scripts_added:Math.max(0,document.scripts.length-xe)},n.events={untrusted_clicks:te,any_input:ne}}function je(){n.main&&n.main.uach&&!(n.worker&&n.worker.uach)&&delete n.main.uach.full_version_list}function q(e){for(var t=0,l=0;l<e.length;l+=1){var a=e.charCodeAt(l);a<128?t+=1:a<2048?t+=2:a>=55296&&a<=56319?(t+=4,l+=1):t+=3}return t}function v(e,t){n[e]&&delete n[e][t]}function Ue(){var e="compared",t="input";function l(){return n.xrealm=Te(n.main,n.worker,n.iframe),JSON.stringify(n)}for(var a=l(),c=[[e,()=>{["main","worker","iframe"].forEach(u=>{n[u]&&n[u].uach&&delete n[u].uach.full_version_list})}],[t,()=>{n.globals.late=n.globals.late.slice(0,8)}],[e,()=>v("iframe","uach")],[e,()=>v("worker","uach")],[e,()=>v("main","uach")],[e,()=>v("iframe","webgl")],[e,()=>v("worker","webgl")],[e,()=>v("iframe","ua")],[e,()=>v("worker","ua")],[t,()=>{n.proto.main=n.proto.main.slice(0,4)}],[t,()=>delete n.iframe],[t,()=>delete n.worker],[t,()=>v("main","webgl")],[t,()=>v("main","ua")],[t,()=>delete n.globals],[t,()=>delete n.main],[t,()=>delete n.proto]],o=0;o<c.length&&q(a)>J;o+=1){var r=a,E=JSON.stringify(n.xrealm);c[o][1](),a=l();var g=a!==r&&(c[o][0]===t||JSON.stringify(n.xrealm)!==E);g&&n.availability==="available"&&(n.availability="insufficient-observation",a=l())}if(G&&D&&D.reading.state==="observed"&&n.main&&n.main.os_fonts){n.nonce=G,n.env={rev:_e,fonts:D.reading.value},delete n.main.os_fonts;var m=JSON.stringify(n);if(q(m)<=J)return m}return a}function T(e){if(!w){w=!0,n.availability=e||(document.visibilityState==="hidden"?"background-tab":Q?"unsupported-api":R?"script-failure":S&&P&&L?"available":"insufficient-observation"),De(),Me();var t=Ue();q(t)>J||p(()=>{fetch(ye,{method:"POST",body:t,keepalive:!0,credentials:"omit",headers:{"content-type":"text/plain"}}).catch(()=>{})})}}})`;
7
771
 
8
772
  // ../connector-core/src/api-environment.ts
9
773
  var STEADPHAST_API_KEY_ENV_VAR = "STEADPHAST_API_KEY";
@@ -17,6 +781,7 @@ var ENVELOPE_INGEST_PATHNAME = "/v1/connectors/nextjs/events";
17
781
  var BEACON_PATHNAME = "/v1/client/t0";
18
782
  var COLLECTOR_HEADER_PREFIX = "x-steadphast-collector-";
19
783
  var COLLECTOR_CONTEXT_HEADER = `${COLLECTOR_HEADER_PREFIX}context`;
784
+ var BEHAVIORAL_CONTEXT_HEADER = `${COLLECTOR_HEADER_PREFIX}behavioral`;
20
785
  var LEGACY_CANONICAL_INGEST_PATHNAME = "/v1/events";
21
786
  var DiscoverConfigError = class extends TypeError {
22
787
  name = "DiscoverConfigError";
@@ -98,6 +863,9 @@ var API_KEY_VERIFIER_DOMAIN = "steadphast-discover:api-key:v1";
98
863
  var NONCE_KEY_SALT = "steadphast-discover/client-nonce/v1/salt";
99
864
  var NONCE_KEY_INFO = "steadphast-discover/client-nonce/v1";
100
865
  var RENDER_CONTEXT_DOMAIN = "steadphast-discover/collector-render/v1";
866
+ var T1_KEY_SALT = "steadphast-discover/client-t1/v1/salt";
867
+ var T1_KEY_INFO = "steadphast-discover/client-t1/v1";
868
+ var T1_RENDER_DOMAIN = "steadphast-discover/behavioral-render/v1";
101
869
  var MAX_RID_BYTES = 512;
102
870
  var MAX_KEY_ID_BYTES = 64;
103
871
  var TAG_BYTES = 32;
@@ -121,7 +889,72 @@ function createNonceMinter(apiKey) {
121
889
  }
122
890
  const keyIdBytes = utf8(parsed.keyId);
123
891
  let nonceKey;
892
+ let t1Key;
124
893
  return {
894
+ async mintBehavioralContext(context) {
895
+ t1Key ??= deriveNonceKey(parsed, keyIdBytes, T1_KEY_SALT, T1_KEY_INFO);
896
+ const header = utf8(JSON.stringify(context));
897
+ const tag = new Uint8Array(
898
+ await crypto.subtle.sign(
899
+ "HMAC",
900
+ await t1Key,
901
+ concat(utf8(T1_RENDER_DOMAIN), header)
902
+ )
903
+ );
904
+ const wire = bytes(header.byteLength + TAG_BYTES);
905
+ wire.set(header);
906
+ wire.set(tag, header.byteLength);
907
+ return base64UrlNoPad(wire);
908
+ },
909
+ async behavioralFromContext(context, policy) {
910
+ if (context.length > 2048 || policy.mode !== "own") return void 0;
911
+ try {
912
+ const binary = atob(context.replace(/-/g, "+").replace(/_/g, "/"));
913
+ const wire = bytes(binary.length);
914
+ for (let i = 0; i < binary.length; i++) wire[i] = binary.charCodeAt(i);
915
+ if (wire.length <= TAG_BYTES) return void 0;
916
+ const header = wire.subarray(0, -TAG_BYTES);
917
+ t1Key ??= deriveNonceKey(parsed, keyIdBytes, T1_KEY_SALT, T1_KEY_INFO);
918
+ if (!await crypto.subtle.verify(
919
+ "HMAC",
920
+ await t1Key,
921
+ wire.subarray(-TAG_BYTES),
922
+ concat(utf8(T1_RENDER_DOMAIN), header)
923
+ ))
924
+ return void 0;
925
+ const input = JSON.parse(
926
+ new TextDecoder().decode(header)
927
+ );
928
+ if (Date.now() - input.issued_at_ms > 6e5 || input.issued_at_ms > Date.now() + 3e4)
929
+ return void 0;
930
+ const binding = utf8(
931
+ JSON.stringify({
932
+ version: 1,
933
+ key_id: parsed.keyId,
934
+ source: input.source,
935
+ rid: input.rid,
936
+ site: input.site,
937
+ issued_at_ms: input.issued_at_ms,
938
+ expires_at_ms: input.issued_at_ms + 6e5,
939
+ revision: policy.revision,
940
+ timing_enabled: policy.timing_enabled
941
+ })
942
+ );
943
+ const tag = new Uint8Array(
944
+ await crypto.subtle.sign("HMAC", await t1Key, binding)
945
+ );
946
+ const token = bytes(binding.byteLength + TAG_BYTES);
947
+ token.set(binding);
948
+ token.set(tag, binding.byteLength);
949
+ return {
950
+ nonce: base64UrlNoPad(token),
951
+ path: input.path,
952
+ issuedAt: input.issued_at_ms
953
+ };
954
+ } catch {
955
+ return void 0;
956
+ }
957
+ },
125
958
  async mintRenderContext(rid, servedAtMs) {
126
959
  const header = encodeHeader(rid, servedAtMs, keyIdBytes);
127
960
  if (header === void 0) return void 0;
@@ -138,7 +971,7 @@ function createNonceMinter(apiKey) {
138
971
  context.set(tag, header.byteLength);
139
972
  return base64UrlNoPad(context);
140
973
  },
141
- async nonceFromRenderContext(context) {
974
+ async nonceFromRenderContext(context, rendering) {
142
975
  if (context.length > 850 || !/^[A-Za-z0-9_-]+$/.test(context)) {
143
976
  return void 0;
144
977
  }
@@ -161,10 +994,29 @@ function createNonceMinter(apiKey) {
161
994
  concat(utf8(RENDER_CONTEXT_DOMAIN), header)
162
995
  ))
163
996
  return void 0;
164
- const tag = new Uint8Array(
165
- await crypto.subtle.sign("HMAC", await nonceKey, header)
997
+ let signed = header;
998
+ if (rendering !== void 0) {
999
+ const { revision, catalog } = rendering;
1000
+ if (![revision, catalog].every(
1001
+ (n) => Number.isInteger(n) && n >= 0 && n <= 4294967295
1002
+ ) || revision === 0)
1003
+ return void 0;
1004
+ const extended = bytes(header.byteLength + 9 + TAG_BYTES);
1005
+ extended.set(header);
1006
+ extended[0] = 2;
1007
+ extended[header.byteLength] = 4;
1008
+ const view = new DataView(extended.buffer);
1009
+ view.setUint32(header.byteLength + 1, revision);
1010
+ view.setUint32(header.byteLength + 5, catalog);
1011
+ decoded = extended;
1012
+ signed = extended.subarray(0, -TAG_BYTES);
1013
+ }
1014
+ decoded.set(
1015
+ new Uint8Array(
1016
+ await crypto.subtle.sign("HMAC", await nonceKey, signed)
1017
+ ),
1018
+ signed.byteLength
166
1019
  );
167
- decoded.set(tag, header.byteLength);
168
1020
  return base64UrlNoPad(decoded);
169
1021
  }
170
1022
  };
@@ -192,7 +1044,7 @@ function encodeHeader(rid, servedAtMs, keyIdBytes) {
192
1044
  header.set(keyIdBytes, offset);
193
1045
  return header;
194
1046
  }
195
- async function deriveNonceKey(parsed, keyIdBytes) {
1047
+ async function deriveNonceKey(parsed, keyIdBytes, salt = NONCE_KEY_SALT, info = NONCE_KEY_INFO) {
196
1048
  const secretKey = await crypto.subtle.importKey(
197
1049
  "raw",
198
1050
  utf8(parsed.secret),
@@ -212,8 +1064,8 @@ async function deriveNonceKey(parsed, keyIdBytes) {
212
1064
  {
213
1065
  name: "HKDF",
214
1066
  hash: "SHA-256",
215
- salt: utf8(NONCE_KEY_SALT),
216
- info: concat(utf8(NONCE_KEY_INFO), keyIdBytes)
1067
+ salt: utf8(salt),
1068
+ info: concat(utf8(info), keyIdBytes)
217
1069
  },
218
1070
  hkdfKey,
219
1071
  TAG_BYTES * 8
@@ -258,35 +1110,175 @@ var NonceMinterCache = class {
258
1110
  }
259
1111
  };
260
1112
 
1113
+ // src/page-probes.ts
1114
+ function createProbeRunner() {
1115
+ let remaining = 1500;
1116
+ let busy = false;
1117
+ const queue = [];
1118
+ const jobs = /* @__PURE__ */ new Map();
1119
+ function next() {
1120
+ if (!busy) queue.shift()?.();
1121
+ }
1122
+ return {
1123
+ run(module, name, route, permitted, start) {
1124
+ const key = `${module}:${name}`;
1125
+ const job = {
1126
+ reading: { module, name, route, state: "not-observed", value: null },
1127
+ cancel() {
1128
+ cancelled = true;
1129
+ stop?.();
1130
+ }
1131
+ };
1132
+ let cancelled = false;
1133
+ let stop;
1134
+ if (permitted !== true) return job;
1135
+ const prior = jobs.get(key);
1136
+ if (prior) return prior;
1137
+ jobs.set(key, job);
1138
+ queue.push(() => {
1139
+ if (cancelled || remaining <= 0 || typeof AbortController === "undefined") {
1140
+ next();
1141
+ return;
1142
+ }
1143
+ busy = true;
1144
+ const controller = new AbortController();
1145
+ const began = performance.now();
1146
+ const timer = setTimeout(() => {
1147
+ remaining = 0;
1148
+ finish();
1149
+ }, remaining);
1150
+ function finish(value, state = "observed") {
1151
+ if (!stop) return;
1152
+ stop = void 0;
1153
+ clearTimeout(timer);
1154
+ remaining -= Math.max(0, performance.now() - began);
1155
+ if (remaining > 0 && value !== void 0 && Number.isFinite(value))
1156
+ job.reading = { module, name, route, state, value };
1157
+ controller.abort();
1158
+ busy = false;
1159
+ next();
1160
+ }
1161
+ stop = () => finish();
1162
+ try {
1163
+ start(finish, controller.signal);
1164
+ } catch {
1165
+ finish();
1166
+ }
1167
+ });
1168
+ next();
1169
+ return job;
1170
+ }
1171
+ };
1172
+ }
1173
+ function pageScript(invocations) {
1174
+ return `(()=>{const key=Symbol.for("steadphast.page-sdk");if(Object.prototype.hasOwnProperty.call(document,key))return;Object.defineProperty(document,key,{value:true});const sdk=(${createProbeRunner.toString()})();${invocations}})()`;
1175
+ }
1176
+
261
1177
  // src/collector-render.ts
262
1178
  var minters = new NonceMinterCache();
263
- function collectorScript(nonce, endpoint) {
264
- const embed = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
265
- return `${COLLECTOR_SOURCE}(${embed(nonce)},${embed(endpoint)});`;
1179
+ function collectorScript(nonce, endpoint, rendering) {
1180
+ const args = rendering ? [nonce, endpoint, rendering.nonce, rendering.catalog] : [nonce, endpoint];
1181
+ return `${COLLECTOR_SOURCE}(sdk,${args.map((v) => JSON.stringify(v).replace(/</g, "\\u003c")).join(",")});`;
266
1182
  }
267
- async function renderCollector(config, endpoint, cspNonce) {
268
- if (config.collector !== true) return null;
1183
+ async function renderCollector(config, endpoint, cspNonce, environmentPermitted = false) {
1184
+ if (config.collector === false || config.collector !== true && (config.behavioral?.mode ?? "own") !== "own")
1185
+ return null;
269
1186
  validateApiKeyEnvVar(config.apiKeyEnvVar);
270
- const context = (await headers()).get(COLLECTOR_CONTEXT_HEADER);
271
- if (context === null) return null;
1187
+ const requestHeaders = await headers();
1188
+ const context = requestHeaders.get(COLLECTOR_CONTEXT_HEADER);
1189
+ const behavioralContext = requestHeaders.get(BEHAVIORAL_CONTEXT_HEADER);
1190
+ if (context === null && behavioralContext === null) return null;
272
1191
  const apiKey = resolveApiKey(config.apiKeyEnvVar);
273
1192
  if (apiKey === void 0) return null;
274
1193
  const minter = minters.for(apiKey);
275
1194
  if (minter === void 0) return null;
276
- const nonce = await minter.nonceFromRenderContext(context);
277
- if (nonce === void 0) return null;
1195
+ const nonce = context === null ? void 0 : await minter.nonceFromRenderContext(context);
1196
+ let script = "";
1197
+ if (config.collector === true && context !== null && nonce !== void 0) {
1198
+ let rendering;
1199
+ if (environmentPermitted === true && config.environment?.rendering === true) {
1200
+ try {
1201
+ const response = await fetch(
1202
+ new URL("/v1/connectors/nextjs/environment-policy", endpoint),
1203
+ {
1204
+ headers: { authorization: `Bearer ${apiKey}` },
1205
+ cache: "no-store",
1206
+ redirect: "error",
1207
+ signal: AbortSignal.timeout(250)
1208
+ }
1209
+ );
1210
+ if (response.ok) {
1211
+ const policy = await response.json();
1212
+ if (policy?.rendering_enabled === true) {
1213
+ const extended = await minter.nonceFromRenderContext(context, {
1214
+ revision: policy.revision,
1215
+ catalog: policy.catalog_revision
1216
+ });
1217
+ if (extended)
1218
+ rendering = { nonce: extended, catalog: policy.catalog_revision };
1219
+ }
1220
+ }
1221
+ } catch {
1222
+ }
1223
+ }
1224
+ script = collectorScript(nonce, endpoint, rendering);
1225
+ }
1226
+ if ((config.behavioral?.mode ?? "own") === "own" && behavioralContext !== null) {
1227
+ try {
1228
+ const response = await fetch(
1229
+ new URL("/v1/connectors/nextjs/behavioral-policy", endpoint),
1230
+ {
1231
+ headers: { authorization: `Bearer ${apiKey}` },
1232
+ cache: "no-store",
1233
+ signal: AbortSignal.timeout(250)
1234
+ }
1235
+ );
1236
+ const policy = await response.json();
1237
+ if (response.ok && policy.mode === "own" && typeof policy.timing_enabled === "boolean" && Number.isInteger(policy.revision) && policy.revision >= 0 && policy.revision <= 4294967295) {
1238
+ const timing = config.behavioral?.timing === true && policy.timing_enabled;
1239
+ const binding = await minter.behavioralFromContext(behavioralContext, {
1240
+ ...policy,
1241
+ timing_enabled: timing
1242
+ });
1243
+ if (binding && config.behavioral?.routes?.includes(binding.path)) {
1244
+ const args = JSON.stringify([
1245
+ binding.nonce,
1246
+ new URL("/v1/client/t1", endpoint).href,
1247
+ timing,
1248
+ binding.issuedAt,
1249
+ binding.path,
1250
+ // No prompt only when both the deployed site and the workspace say "notice".
1251
+ config.behavioral.consentBasis === "notice" && policy.consent_basis === "notice",
1252
+ // Target boxes only when both the site and the workspace turn path capture on; a
1253
+ // policy without the field (a server before path capture) reads as off.
1254
+ config.behavioral.pathCapture === true && "path_capture_enabled" in policy && policy.path_capture_enabled === true,
1255
+ config.behavioral.timingRoute ?? "steadphast-host"
1256
+ ]).replace(/</g, "\\u003c");
1257
+ script += `;(${behavioralCollector.toString()})(sdk,...${args});`;
1258
+ }
1259
+ }
1260
+ } catch {
1261
+ }
1262
+ }
1263
+ if (script === "") return null;
278
1264
  return createElement("script", {
279
1265
  nonce: cspNonce ?? nonce,
280
1266
  // biome-ignore lint/security/noDangerouslySetInnerHtml: package-owned collector with JSON-encoded, script-escaped arguments; no visitor nonce or destination is used.
281
- dangerouslySetInnerHTML: { __html: collectorScript(nonce, endpoint) }
1267
+ dangerouslySetInnerHTML: { __html: pageScript(script) }
282
1268
  });
283
1269
  }
284
1270
 
285
1271
  // src/server.ts
286
1272
  async function DiscoverCollector(props = {}) {
287
- if (props.config?.collector !== true) return null;
1273
+ if (!props.config || props.config.collector === false || props.config.collector !== true && ((props.config.behavioral?.mode ?? "own") !== "own" || !props.config.behavioral?.routes?.length))
1274
+ return null;
288
1275
  const endpoint = `${new URL(resolveProductionIngestUrl(props.config.apiUrl)).origin}${BEACON_PATHNAME}`;
289
- return renderCollector(props.config, endpoint, props.nonce);
1276
+ return renderCollector(
1277
+ props.config,
1278
+ endpoint,
1279
+ props.nonce,
1280
+ props.environmentPermitted
1281
+ );
290
1282
  }
291
1283
  export {
292
1284
  DiscoverCollector