@kya-os/checkpoint-shared 1.5.1 → 1.6.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.
Files changed (161) hide show
  1. package/CHANGELOG.md +217 -0
  2. package/dist/beacon-nonce/index.d.mts +36 -0
  3. package/dist/beacon-nonce/index.d.mts.map +1 -0
  4. package/dist/beacon-nonce/index.d.ts +36 -0
  5. package/dist/beacon-nonce/index.d.ts.map +1 -0
  6. package/dist/beacon-nonce/index.js +305 -0
  7. package/dist/beacon-nonce/index.mjs +294 -0
  8. package/dist/beacon-nonce/index.mjs.map +1 -0
  9. package/dist/beacon-types/index.d.mts +40 -0
  10. package/dist/beacon-types/index.d.mts.map +1 -1
  11. package/dist/beacon-types/index.d.ts +40 -0
  12. package/dist/beacon-types/index.d.ts.map +1 -1
  13. package/dist/beacon-types/index.js +53 -5
  14. package/dist/beacon-types/index.mjs +49 -6
  15. package/dist/beacon-types/index.mjs.map +1 -1
  16. package/dist/browser-posture-BuChqmH5.d.mts +169 -0
  17. package/dist/browser-posture-BuChqmH5.d.mts.map +1 -0
  18. package/dist/browser-posture-DIaVLuW3.d.ts +169 -0
  19. package/dist/browser-posture-DIaVLuW3.d.ts.map +1 -0
  20. package/dist/browser-posture-cookie.d.mts +4 -2
  21. package/dist/browser-posture-cookie.d.mts.map +1 -0
  22. package/dist/browser-posture-cookie.d.ts +4 -2
  23. package/dist/browser-posture-cookie.d.ts.map +1 -0
  24. package/dist/browser-posture-cookie.mjs.map +1 -1
  25. package/dist/browser-posture-proof.d.mts +18 -0
  26. package/dist/browser-posture-proof.d.mts.map +1 -0
  27. package/dist/browser-posture-proof.d.ts +18 -0
  28. package/dist/browser-posture-proof.d.ts.map +1 -0
  29. package/dist/browser-posture-proof.js +66 -0
  30. package/dist/browser-posture-proof.mjs +63 -0
  31. package/dist/browser-posture-proof.mjs.map +1 -0
  32. package/dist/browser-posture-report.d.mts +59 -2
  33. package/dist/browser-posture-report.d.mts.map +1 -1
  34. package/dist/browser-posture-report.d.ts +59 -2
  35. package/dist/browser-posture-report.d.ts.map +1 -1
  36. package/dist/browser-posture-report.js +1 -1
  37. package/dist/browser-posture-report.mjs +1 -1
  38. package/dist/browser-posture-report.mjs.map +1 -1
  39. package/dist/browser-posture.d.mts +2 -85
  40. package/dist/browser-posture.d.ts +2 -85
  41. package/dist/browser-posture.js +207 -45
  42. package/dist/browser-posture.mjs +195 -45
  43. package/dist/browser-posture.mjs.map +1 -1
  44. package/dist/browser.d.mts +0 -8
  45. package/dist/browser.d.mts.map +1 -1
  46. package/dist/browser.d.ts +0 -8
  47. package/dist/browser.d.ts.map +1 -1
  48. package/dist/browser.js +1 -1
  49. package/dist/browser.mjs +1 -1
  50. package/dist/browser.mjs.map +1 -1
  51. package/dist/clearance.d.mts +1 -1
  52. package/dist/clearance.d.ts +1 -1
  53. package/dist/clearance.js +2 -2
  54. package/dist/clearance.mjs +2 -2
  55. package/dist/{client-ip-HOfe6ucV.mjs → client-ip-B2Xeo-GK.mjs} +2 -2
  56. package/dist/{client-ip-HOfe6ucV.mjs.map → client-ip-B2Xeo-GK.mjs.map} +1 -1
  57. package/dist/{client-ip-1y2iXAYW.js → client-ip-CW6pRyLf.js} +1 -1
  58. package/dist/consent-handoff.d.mts +41 -0
  59. package/dist/consent-handoff.d.mts.map +1 -0
  60. package/dist/consent-handoff.d.ts +41 -0
  61. package/dist/consent-handoff.d.ts.map +1 -0
  62. package/dist/consent-handoff.js +1 -0
  63. package/dist/consent-handoff.mjs +2 -0
  64. package/dist/consent-handoff.mjs.map +1 -0
  65. package/dist/errors/index.d.mts +155 -0
  66. package/dist/errors/index.d.mts.map +1 -1
  67. package/dist/errors/index.d.ts +155 -0
  68. package/dist/errors/index.d.ts.map +1 -1
  69. package/dist/errors/index.js +513 -9
  70. package/dist/errors/index.mjs +513 -10
  71. package/dist/errors/index.mjs.map +1 -1
  72. package/dist/{external-jr_S4iSS.d.ts → external-B7WI9FyQ.d.mts} +2 -2
  73. package/dist/{external-jr_S4iSS.d.mts.map → external-B7WI9FyQ.d.mts.map} +1 -1
  74. package/dist/{external-jr_S4iSS.d.mts → external-B7WI9FyQ.d.ts} +2 -2
  75. package/dist/{external-jr_S4iSS.d.ts.map → external-B7WI9FyQ.d.ts.map} +1 -1
  76. package/dist/gateway-client-ip.d.mts +1 -1
  77. package/dist/gateway-client-ip.d.ts +1 -1
  78. package/dist/gateway-client-ip.js +2 -2
  79. package/dist/gateway-client-ip.mjs +2 -2
  80. package/dist/index.d.mts +6375 -1532
  81. package/dist/index.d.mts.map +1 -1
  82. package/dist/index.d.ts +6375 -1532
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +5629 -697
  85. package/dist/index.mjs +5341 -683
  86. package/dist/index.mjs.map +1 -1
  87. package/dist/mcpi/approval-grant/index.d.mts +1 -1
  88. package/dist/mcpi/approval-grant/index.d.mts.map +1 -1
  89. package/dist/mcpi/approval-grant/index.d.ts +1 -1
  90. package/dist/mcpi/approval-grant/index.d.ts.map +1 -1
  91. package/dist/mcpi/approval-grant/index.js +58 -49
  92. package/dist/mcpi/approval-grant/index.mjs +58 -49
  93. package/dist/mcpi/approval-grant/index.mjs.map +1 -1
  94. package/dist/mcpi/dashboard-config/index.d.mts +3 -2
  95. package/dist/mcpi/dashboard-config/index.d.mts.map +1 -1
  96. package/dist/mcpi/dashboard-config/index.d.ts +3 -2
  97. package/dist/mcpi/dashboard-config/index.d.ts.map +1 -1
  98. package/dist/posture-origins/index.d.mts +41 -0
  99. package/dist/posture-origins/index.d.mts.map +1 -0
  100. package/dist/posture-origins/index.d.ts +41 -0
  101. package/dist/posture-origins/index.d.ts.map +1 -0
  102. package/dist/posture-origins/index.js +441 -0
  103. package/dist/posture-origins/index.mjs +430 -0
  104. package/dist/posture-origins/index.mjs.map +1 -0
  105. package/dist/posture-origins-LFkX80oF.js +627 -0
  106. package/dist/posture-origins-Pn-ii-Pp.mjs +533 -0
  107. package/dist/posture-origins-Pn-ii-Pp.mjs.map +1 -0
  108. package/dist/{project-verification-key-CgSVX9_m.mjs → project-verification-key-66N4edKn.mjs} +2 -2
  109. package/dist/{project-verification-key-CgSVX9_m.mjs.map → project-verification-key-66N4edKn.mjs.map} +1 -1
  110. package/dist/{project-verification-key-C3L5rd8a.js → project-verification-key-BccT12tQ.js} +1 -1
  111. package/dist/rules.json +0 -1
  112. package/dist/{schemas-DxY-dk9y.mjs → schemas-7qodsG-Z.mjs} +49 -2
  113. package/dist/schemas-7qodsG-Z.mjs.map +1 -0
  114. package/dist/{schemas-BmjNLAE7.js → schemas-YhagYDx_.js} +59 -0
  115. package/dist/signals/index.d.mts +75 -55
  116. package/dist/signals/index.d.mts.map +1 -1
  117. package/dist/signals/index.d.ts +75 -55
  118. package/dist/signals/index.d.ts.map +1 -1
  119. package/dist/signals/index.js +246 -2
  120. package/dist/signals/index.mjs +236 -3
  121. package/dist/signals/index.mjs.map +1 -1
  122. package/fixtures/browser-integrity/captured-java-0.2.1-missing-score.json +10 -0
  123. package/fixtures/browser-integrity/null-score.json +11 -0
  124. package/fixtures/browser-integrity/numeric-score.json +11 -0
  125. package/fixtures/browser-posture-claims.json +168 -0
  126. package/fixtures/browser-posture-headers.json +6 -0
  127. package/fixtures/cli-registration.v2.json +115 -0
  128. package/fixtures/detection/reason-codes.json +1 -1
  129. package/fixtures/kya-http/README.md +34 -25
  130. package/fixtures/kya-http/consent-handoff.codes.json +34 -0
  131. package/fixtures/kya-http/protected-resource-metadata.full.json +14 -5
  132. package/fixtures/kya-http/protected-resource-metadata.invalid-issuer.json +51 -0
  133. package/fixtures/kya-http/protected-resource-metadata.no-issuer.json +32 -0
  134. package/fixtures/reviewer-grant-revocation.v1.json +285 -0
  135. package/fixtures/workbench/a2a-signed-request.v1.json +255 -0
  136. package/fixtures/workbench/artifact-bindings.v1.json +1003 -0
  137. package/fixtures/workbench/delegation-management.v1.json +507 -0
  138. package/fixtures/workbench/didcomm-task-source.v1.json +191 -0
  139. package/fixtures/workbench/graph-interfaces.v1.json +1887 -0
  140. package/fixtures/workbench/identity-provisioning.v1.json +643 -0
  141. package/fixtures/workbench/linear-installation.v1.json +484 -0
  142. package/fixtures/workbench/management-session.v1.json +716 -0
  143. package/fixtures/workbench/model-credentials.v1.json +630 -0
  144. package/fixtures/workbench/source-claim-pooled.v1.json +50 -0
  145. package/fixtures/workbench/task-grant.v1.json +695 -0
  146. package/fixtures/workbench/task-status-projection.v1.json +591 -0
  147. package/fixtures/workbench/workload-enrollment.v1.json +580 -0
  148. package/package.json +24 -5
  149. package/src/data/compiled/merged-rules.json +2 -9
  150. package/src/data/default-rules.json +0 -1
  151. package/dist/browser-posture-cookie-Dmq9Brf_.d.mts +0 -5
  152. package/dist/browser-posture-cookie-Dmq9Brf_.d.mts.map +0 -1
  153. package/dist/browser-posture-cookie-Dmq9Brf_.d.ts +0 -5
  154. package/dist/browser-posture-cookie-Dmq9Brf_.d.ts.map +0 -1
  155. package/dist/browser-posture.d.mts.map +0 -1
  156. package/dist/browser-posture.d.ts.map +0 -1
  157. package/dist/patterns-CkRVOdtV.js +0 -243
  158. package/dist/patterns-DzkGy_qk.mjs +0 -173
  159. package/dist/patterns-DzkGy_qk.mjs.map +0 -1
  160. package/dist/schemas-DxY-dk9y.mjs.map +0 -1
  161. package/fixtures/kya-http/protected-resource-metadata.global.json +0 -28
@@ -41,13 +41,26 @@ function booleanOr(value, fallback, onReject) {
41
41
  onReject?.(value);
42
42
  return fallback;
43
43
  }
44
+ /** Ingest's own `sessionId` bound (1-255), limited to characters a cookie value carries unescaped. */
45
+ const RESUMABLE_SESSION_ID = /^[A-Za-z0-9._~-]{1,255}$/;
46
+ function resumableSessionId(value, onReject) {
47
+ if (value === void 0) return void 0;
48
+ if (typeof value === "string" && RESUMABLE_SESSION_ID.test(value)) return value;
49
+ onReject?.(value);
50
+ }
51
+ function receiptCallback(value, onReject) {
52
+ if (value === void 0) return void 0;
53
+ if (typeof value === "function") return value;
54
+ onReject?.(value);
55
+ }
44
56
  const DISPATCH_TRIGGER_NAMES = [
45
57
  "arrival",
46
58
  "signals",
47
59
  "interaction",
48
60
  "untrusted",
49
61
  "posture",
50
- "unload"
62
+ "unload",
63
+ "navigation"
51
64
  ];
52
65
  /**
53
66
  * Keeps only the known trigger names with a real boolean; anything else is
@@ -144,7 +157,7 @@ function parseOfflineQueueEntry(input) {
144
157
  if (!isRecord(input)) throw new Error("Invalid offline queue entry");
145
158
  const entry = input;
146
159
  return {
147
- id: stringOr(entry.id, `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`),
160
+ id: stringOr(entry.id, `${Date.now()}_${Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(6)), (byte) => byte.toString(16).padStart(2, "0")).join("")}`),
148
161
  events: Array.isArray(entry.events) ? entry.events : [],
149
162
  timestamp: numberOr(entry.timestamp, Date.now()),
150
163
  expiresAt: numberOr(entry.expiresAt, Date.now() + 864e5),
@@ -152,10 +165,17 @@ function parseOfflineQueueEntry(input) {
152
165
  size: numberOr(entry.size, 0)
153
166
  };
154
167
  }
168
+ function randomId() {
169
+ const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
170
+ bytes[6] = bytes[6] & 15 | 64;
171
+ bytes[8] = bytes[8] & 63 | 128;
172
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
173
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
174
+ }
155
175
  function parseBeaconWorkerMessage(input) {
156
176
  if (!isRecord(input)) throw new Error("Invalid beacon worker message");
157
177
  const msg = input;
158
- const messageId = stringOr(msg.messageId) ?? stringOr(msg.id) ?? crypto.randomUUID();
178
+ const messageId = stringOr(msg.messageId) ?? stringOr(msg.id) ?? randomId();
159
179
  return {
160
180
  type: isBeaconWorkerMessageType(msg.type) ? msg.type : "init",
161
181
  data: msg.data,
@@ -178,7 +198,7 @@ function parseWorkerMessage(input) {
178
198
  const msg = input && typeof input === "object" ? input : null;
179
199
  if (!msg) throw new Error("Invalid worker message");
180
200
  return {
181
- id: msg.id || crypto.randomUUID(),
201
+ id: msg.id || randomId(),
182
202
  type: isWorkerMessageType(msg.type) ? msg.type : "request",
183
203
  action: msg.action,
184
204
  payload: msg.payload,
@@ -281,12 +301,15 @@ function parseBeaconConfig(input, onWarn) {
281
301
  debug: config.debug === true,
282
302
  logLevel: isLogLevel(config.logLevel) ? config.logLevel : "error",
283
303
  respectDoNotTrack: config.respectDoNotTrack !== false,
304
+ requireConsent: config.requireConsent === true,
284
305
  anonymizeIp: config.anonymizeIp === true,
285
306
  stripUrlFragment: config.stripUrlFragment !== false,
286
307
  scrubQueryParams: isStringArray(config.scrubQueryParams) ? config.scrubQueryParams : void 0,
287
308
  dropQueryParams: config.dropQueryParams === true,
288
- sessionTimeout: numberOr(config.sessionTimeout, 18e5),
309
+ sessionTimeout: numberOr(config.sessionTimeout, void 0),
289
310
  sessionCookieName: stringOr(config.sessionCookieName, "_as_beacon_session"),
311
+ browserSessionId: resumableSessionId(config.browserSessionId, (received) => onWarn?.(`browserSessionId must match ${RESUMABLE_SESSION_ID} (received ${JSON.stringify(received)}); ignoring it`)),
312
+ onReceipt: receiptCallback(config.onReceipt, (received) => onWarn?.(`onReceipt must be a function (received ${typeof received}); ignoring it`)),
290
313
  batchSize: typeof config.batchSize === "number" ? config.batchSize : void 0,
291
314
  flushInterval: typeof config.flushInterval === "number" ? config.flushInterval : void 0,
292
315
  collectorDeadlineMs: numberOr(config.collectorDeadlineMs, 1600),
@@ -315,23 +338,48 @@ function parseBeaconConfig(input, onWarn) {
315
338
  * the SDK's offline drain never dequeues more than this per request.
316
339
  */
317
340
  const BEACON_MAX_EVENTS_PER_BATCH = 100;
341
+ const SESSION_IDLE_GAP_MAX_MS = 216e5;
342
+ const BEACON_MAX_BATCH_ID_LENGTH = 255;
343
+ const BEACON_ORIGIN_CONTRACT_VERSION = 1;
344
+ const BEACON_ORIGIN_CAPABILITIES = [
345
+ "batch-replay-v1",
346
+ "receipt-status-v1",
347
+ "receipt-posture-v1"
348
+ ];
318
349
  /**
319
350
  * Lifetime of the signed browser posture token, in seconds. Defined here and
320
351
  * re-exported by `browser-posture.ts` (which imports `jose`) so the
321
352
  * size-budgeted beacon bundle can read it without pulling in a JWT library.
322
353
  */
323
354
  const POSTURE_TTL_SECONDS = 120;
355
+ function parsePostureAnswer(value) {
356
+ if (!isRecord(value)) return {};
357
+ const answer = {};
358
+ if (isRecord(value.posture) && typeof value.posture.token === "string" && value.posture.token.length > 0 && typeof value.posture.expiresAt === "number" && Number.isFinite(value.posture.expiresAt)) answer.posture = {
359
+ token: value.posture.token,
360
+ expiresAt: value.posture.expiresAt
361
+ };
362
+ else if (typeof value.postureStatus === "string" && value.postureStatus.length <= 64) answer.postureStatus = value.postureStatus;
363
+ if (typeof value.sessionId === "string" && value.sessionId.length <= 255) answer.sessionId = value.sessionId;
364
+ if (typeof value.answeredAtMs === "number" && Number.isFinite(value.answeredAtMs)) answer.answeredAtMs = value.answeredAtMs;
365
+ return answer;
366
+ }
324
367
 
325
368
  //#endregion
369
+ exports.BEACON_MAX_BATCH_ID_LENGTH = BEACON_MAX_BATCH_ID_LENGTH;
326
370
  exports.BEACON_MAX_EVENTS_PER_BATCH = BEACON_MAX_EVENTS_PER_BATCH;
371
+ exports.BEACON_ORIGIN_CAPABILITIES = BEACON_ORIGIN_CAPABILITIES;
372
+ exports.BEACON_ORIGIN_CONTRACT_VERSION = BEACON_ORIGIN_CONTRACT_VERSION;
327
373
  exports.POSTURE_TTL_SECONDS = POSTURE_TTL_SECONDS;
328
374
  exports.ResourceUsageSchema = ResourceUsageSchema;
375
+ exports.SESSION_IDLE_GAP_MAX_MS = SESSION_IDLE_GAP_MAX_MS;
329
376
  exports.WorkerPoolConfigSchema = WorkerPoolConfigSchema;
330
377
  exports.isBeaconIdentity = isBeaconIdentity;
331
378
  exports.parseBeaconConfig = parseBeaconConfig;
332
379
  exports.parseBeaconWorkerMessage = parseBeaconWorkerMessage;
333
380
  exports.parseCircuitBreakerConfig = parseCircuitBreakerConfig;
334
381
  exports.parseOfflineQueueEntry = parseOfflineQueueEntry;
382
+ exports.parsePostureAnswer = parsePostureAnswer;
335
383
  exports.parseResourceUsage = parseResourceUsage;
336
384
  exports.parseRetryStrategy = parseRetryStrategy;
337
385
  exports.parseWorkerCapabilities = parseWorkerCapabilities;
@@ -40,13 +40,26 @@ function booleanOr(value, fallback, onReject) {
40
40
  onReject?.(value);
41
41
  return fallback;
42
42
  }
43
+ /** Ingest's own `sessionId` bound (1-255), limited to characters a cookie value carries unescaped. */
44
+ const RESUMABLE_SESSION_ID = /^[A-Za-z0-9._~-]{1,255}$/;
45
+ function resumableSessionId(value, onReject) {
46
+ if (value === void 0) return void 0;
47
+ if (typeof value === "string" && RESUMABLE_SESSION_ID.test(value)) return value;
48
+ onReject?.(value);
49
+ }
50
+ function receiptCallback(value, onReject) {
51
+ if (value === void 0) return void 0;
52
+ if (typeof value === "function") return value;
53
+ onReject?.(value);
54
+ }
43
55
  const DISPATCH_TRIGGER_NAMES = [
44
56
  "arrival",
45
57
  "signals",
46
58
  "interaction",
47
59
  "untrusted",
48
60
  "posture",
49
- "unload"
61
+ "unload",
62
+ "navigation"
50
63
  ];
51
64
  /**
52
65
  * Keeps only the known trigger names with a real boolean; anything else is
@@ -143,7 +156,7 @@ function parseOfflineQueueEntry(input) {
143
156
  if (!isRecord(input)) throw new Error("Invalid offline queue entry");
144
157
  const entry = input;
145
158
  return {
146
- id: stringOr(entry.id, `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`),
159
+ id: stringOr(entry.id, `${Date.now()}_${Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(6)), (byte) => byte.toString(16).padStart(2, "0")).join("")}`),
147
160
  events: Array.isArray(entry.events) ? entry.events : [],
148
161
  timestamp: numberOr(entry.timestamp, Date.now()),
149
162
  expiresAt: numberOr(entry.expiresAt, Date.now() + 864e5),
@@ -151,10 +164,17 @@ function parseOfflineQueueEntry(input) {
151
164
  size: numberOr(entry.size, 0)
152
165
  };
153
166
  }
167
+ function randomId() {
168
+ const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
169
+ bytes[6] = bytes[6] & 15 | 64;
170
+ bytes[8] = bytes[8] & 63 | 128;
171
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
172
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
173
+ }
154
174
  function parseBeaconWorkerMessage(input) {
155
175
  if (!isRecord(input)) throw new Error("Invalid beacon worker message");
156
176
  const msg = input;
157
- const messageId = stringOr(msg.messageId) ?? stringOr(msg.id) ?? crypto.randomUUID();
177
+ const messageId = stringOr(msg.messageId) ?? stringOr(msg.id) ?? randomId();
158
178
  return {
159
179
  type: isBeaconWorkerMessageType(msg.type) ? msg.type : "init",
160
180
  data: msg.data,
@@ -177,7 +197,7 @@ function parseWorkerMessage(input) {
177
197
  const msg = input && typeof input === "object" ? input : null;
178
198
  if (!msg) throw new Error("Invalid worker message");
179
199
  return {
180
- id: msg.id || crypto.randomUUID(),
200
+ id: msg.id || randomId(),
181
201
  type: isWorkerMessageType(msg.type) ? msg.type : "request",
182
202
  action: msg.action,
183
203
  payload: msg.payload,
@@ -280,12 +300,15 @@ function parseBeaconConfig(input, onWarn) {
280
300
  debug: config.debug === true,
281
301
  logLevel: isLogLevel(config.logLevel) ? config.logLevel : "error",
282
302
  respectDoNotTrack: config.respectDoNotTrack !== false,
303
+ requireConsent: config.requireConsent === true,
283
304
  anonymizeIp: config.anonymizeIp === true,
284
305
  stripUrlFragment: config.stripUrlFragment !== false,
285
306
  scrubQueryParams: isStringArray(config.scrubQueryParams) ? config.scrubQueryParams : void 0,
286
307
  dropQueryParams: config.dropQueryParams === true,
287
- sessionTimeout: numberOr(config.sessionTimeout, 18e5),
308
+ sessionTimeout: numberOr(config.sessionTimeout, void 0),
288
309
  sessionCookieName: stringOr(config.sessionCookieName, "_as_beacon_session"),
310
+ browserSessionId: resumableSessionId(config.browserSessionId, (received) => onWarn?.(`browserSessionId must match ${RESUMABLE_SESSION_ID} (received ${JSON.stringify(received)}); ignoring it`)),
311
+ onReceipt: receiptCallback(config.onReceipt, (received) => onWarn?.(`onReceipt must be a function (received ${typeof received}); ignoring it`)),
289
312
  batchSize: typeof config.batchSize === "number" ? config.batchSize : void 0,
290
313
  flushInterval: typeof config.flushInterval === "number" ? config.flushInterval : void 0,
291
314
  collectorDeadlineMs: numberOr(config.collectorDeadlineMs, 1600),
@@ -314,13 +337,33 @@ function parseBeaconConfig(input, onWarn) {
314
337
  * the SDK's offline drain never dequeues more than this per request.
315
338
  */
316
339
  const BEACON_MAX_EVENTS_PER_BATCH = 100;
340
+ const SESSION_IDLE_GAP_MAX_MS = 216e5;
341
+ const BEACON_MAX_BATCH_ID_LENGTH = 255;
342
+ const BEACON_ORIGIN_CONTRACT_VERSION = 1;
343
+ const BEACON_ORIGIN_CAPABILITIES = [
344
+ "batch-replay-v1",
345
+ "receipt-status-v1",
346
+ "receipt-posture-v1"
347
+ ];
317
348
  /**
318
349
  * Lifetime of the signed browser posture token, in seconds. Defined here and
319
350
  * re-exported by `browser-posture.ts` (which imports `jose`) so the
320
351
  * size-budgeted beacon bundle can read it without pulling in a JWT library.
321
352
  */
322
353
  const POSTURE_TTL_SECONDS = 120;
354
+ function parsePostureAnswer(value) {
355
+ if (!isRecord(value)) return {};
356
+ const answer = {};
357
+ if (isRecord(value.posture) && typeof value.posture.token === "string" && value.posture.token.length > 0 && typeof value.posture.expiresAt === "number" && Number.isFinite(value.posture.expiresAt)) answer.posture = {
358
+ token: value.posture.token,
359
+ expiresAt: value.posture.expiresAt
360
+ };
361
+ else if (typeof value.postureStatus === "string" && value.postureStatus.length <= 64) answer.postureStatus = value.postureStatus;
362
+ if (typeof value.sessionId === "string" && value.sessionId.length <= 255) answer.sessionId = value.sessionId;
363
+ if (typeof value.answeredAtMs === "number" && Number.isFinite(value.answeredAtMs)) answer.answeredAtMs = value.answeredAtMs;
364
+ return answer;
365
+ }
323
366
 
324
367
  //#endregion
325
- export { BEACON_MAX_EVENTS_PER_BATCH, POSTURE_TTL_SECONDS, ResourceUsageSchema, WorkerPoolConfigSchema, isBeaconIdentity, parseBeaconConfig, parseBeaconWorkerMessage, parseCircuitBreakerConfig, parseOfflineQueueEntry, parseResourceUsage, parseRetryStrategy, parseWorkerCapabilities, parseWorkerError, parseWorkerMessage, parseWorkerPoolConfig };
368
+ export { BEACON_MAX_BATCH_ID_LENGTH, BEACON_MAX_EVENTS_PER_BATCH, BEACON_ORIGIN_CAPABILITIES, BEACON_ORIGIN_CONTRACT_VERSION, POSTURE_TTL_SECONDS, ResourceUsageSchema, SESSION_IDLE_GAP_MAX_MS, WorkerPoolConfigSchema, isBeaconIdentity, parseBeaconConfig, parseBeaconWorkerMessage, parseCircuitBreakerConfig, parseOfflineQueueEntry, parsePostureAnswer, parseResourceUsage, parseRetryStrategy, parseWorkerCapabilities, parseWorkerError, parseWorkerMessage, parseWorkerPoolConfig };
326
369
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/beacon-types/index.ts"],"sourcesContent":["/**\n * Public TypeScript types for Checkpoint Beacon\n *\n * This package contains only the public API types needed by beacon consumers.\n * No implementation details or detection rules are included.\n */\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue | undefined };\nexport type BeaconPrimitive = JsonPrimitive;\nexport type BeaconJsonValue = JsonValue;\nexport type BeaconCustomData = Record<string, JsonValue | undefined>;\nexport type BeaconPayload = BeaconCollectorData | BeaconCustomData | null;\nexport type WorkerPayload = unknown;\ntype UnknownRecord = Record<string, unknown>;\n\nfunction isRecord(input: unknown): input is UnknownRecord {\n return typeof input === 'object' && input !== null && !Array.isArray(input);\n}\n\nfunction toRecord(input: unknown): UnknownRecord {\n return isRecord(input) ? input : {};\n}\n\nfunction numberOr(value: unknown, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) && value !== 0 ? value : fallback;\n}\n\n/**\n * Validates a numeric config value against `ok`, falling back to `fallback`\n * when it fails. Only calls `onReject` when the caller actually supplied a\n * value (an `undefined` field, the common case, is not a rejection, it just\n * never overrode the default): H0BB5 (PR #5095 review, item 4) — a rejected\n * value used to fall back silently, with no way for a host to discover a\n * config typo.\n */\nfunction boundedNumberOr(\n value: unknown,\n fallback: number,\n ok: (n: number) => boolean,\n onReject?: (received: unknown) => void\n): number {\n if (typeof value === 'number' && Number.isFinite(value) && ok(value)) return value;\n if (value !== undefined) onReject?.(value);\n return fallback;\n}\n\n/** Same as `boundedNumberOr`, but an absent/rejected value stays `undefined` rather than defaulting. */\nfunction optionalPositiveNumber(\n value: unknown,\n onReject?: (received: unknown) => void\n): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value;\n onReject?.(value);\n return undefined;\n}\n\n/** Same as `optionalPositiveNumber`, without the positivity requirement (a jitter seed may be any finite number). */\nfunction optionalFiniteNumber(\n value: unknown,\n onReject?: (received: unknown) => void\n): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n onReject?.(value);\n return undefined;\n}\n\n/** Same shape as `boundedNumberOr`/`optionalPositiveNumber`, for a boolean config flag. */\nfunction booleanOr(\n value: unknown,\n fallback: boolean,\n onReject?: (received: unknown) => void\n): boolean {\n if (value === undefined) return fallback;\n if (typeof value === 'boolean') return value;\n onReject?.(value);\n return fallback;\n}\n\nconst DISPATCH_TRIGGER_NAMES = [\n 'arrival',\n 'signals',\n 'interaction',\n 'untrusted',\n 'posture',\n 'unload',\n] as const satisfies readonly (keyof BeaconDispatchTriggers)[];\n\n/**\n * Keeps only the known trigger names with a real boolean; anything else is\n * dropped and, when the caller actually named a known trigger with a\n * non-boolean value (`triggers: { posture: 0 }`, say), reported through\n * `onReject` — H0BB5 (PR #5095 review, item 4): a numeric `0` used to be\n * dropped silently and that trigger stayed at its default-enabled state,\n * the opposite of what the \"0 is falsy\" convention suggests.\n */\nfunction pickTriggers(\n value: unknown,\n onReject?: (name: string, received: unknown) => void\n): BeaconDispatchTriggers | undefined {\n if (!isRecord(value)) return undefined;\n const picked: BeaconDispatchTriggers = {};\n for (const name of DISPATCH_TRIGGER_NAMES) {\n const raw = value[name];\n if (typeof raw === 'boolean') {\n picked[name] = raw;\n } else if (raw !== undefined) {\n onReject?.(name, raw);\n }\n }\n return picked;\n}\n\nfunction stringOr(value: unknown, fallback?: string): string | undefined {\n return typeof value === 'string' ? value : fallback;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((entry) => typeof entry === 'string');\n}\n\n/**\n * Non-empty on purpose: an empty schedule would mean \"zero posture-recovery\n * attempts\", silently disabling recovery rather than configuring it. A\n * deployment that actually wants no retries sets `flushInterval` instead.\n */\nfunction isPositiveNumberArray(value: unknown): value is number[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every((entry) => typeof entry === 'number' && Number.isFinite(entry) && entry > 0)\n );\n}\n\nfunction isBeaconTags(value: unknown): value is Record<string, string | number | boolean> {\n return (\n isRecord(value) &&\n Object.values(value).every(\n (entry) =>\n typeof entry === 'string' || typeof entry === 'number' || typeof entry === 'boolean'\n )\n );\n}\n\n/**\n * Exported because `parseBeaconConfig` is an allowlist: a key it does not\n * name is dropped, silently. The beacon's other public entry point\n * (`checkpoint-shared/browser`) carries its own copy of that allowlist, so\n * the CHECK at least lives in one place even while the two parsers do not —\n * see the note on `BeaconConfig.identity`.\n *\n * Rejects an identity with no usable `userId` rather than passing through a\n * half-formed object: downstream this becomes `detections.user_id`, and an\n * empty string there is worse than an absent one — it reads as \"identified\"\n * while naming nobody.\n */\nexport function isBeaconIdentity(value: unknown): value is BeaconIdentity {\n return isRecord(value) && typeof value.userId === 'string' && value.userId.length > 0;\n}\n\nfunction isLogLevel(value: unknown): value is BeaconConfig['logLevel'] {\n return value === 'error' || value === 'warn' || value === 'info' || value === 'debug';\n}\n\nfunction isBeaconWorkerMessageType(value: unknown): value is BeaconWorkerMessageType {\n return (\n value === 'init' ||\n value === 'collect' ||\n value === 'flush' ||\n value === 'config' ||\n value === 'status' ||\n value === 'error' ||\n // `beacon.worker.ts`'s `respond()` has always sent this on every\n // successful request (init/collect/flush/config/status) — the allowlist\n // just never named it, so `parseBeaconWorkerMessage` silently coerced\n // every success response to `'init'` (see that function's fallback).\n value === 'response' ||\n value === 'posture'\n );\n}\n\n/**\n * Resolves whether a beacon should use its Web Worker transport.\n *\n * `enableWebWorker` is accepted as an alias for `useWorker`: the package's\n * own test suite (`checkpoint-beacon/src/index.test.ts`) has always\n * constructed with `enableWebWorker: false`, but `parseBeaconConfig`'s\n * allowlist only ever named `useWorker`, so that key was silently dropped —\n * the beacon kept auto-detecting worker support regardless of what the\n * caller passed. `useWorker` wins when both are set, since it's the\n * canonical name every other config field (`workerUrl`, `workerConfig`)\n * pairs with.\n */\nfunction resolveUseWorker(config: UnknownRecord): boolean {\n if (typeof config.useWorker === 'boolean') {\n return config.useWorker;\n }\n if (typeof config.enableWebWorker === 'boolean') {\n return config.enableWebWorker;\n }\n return true;\n}\n\nexport interface NetworkInformationLike extends EventTarget {\n type?: string;\n effectiveType?: string;\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n}\n\nexport interface NavigatorWithNetworkInformation extends Navigator {\n connection?: NetworkInformationLike;\n mozConnection?: NetworkInformationLike;\n webkitConnection?: NetworkInformationLike;\n deviceMemory?: number;\n vendorSub: string;\n doNotTrack: string | null;\n msDoNotTrack?: string | null;\n}\n\nexport interface WindowWithBeaconMetadata extends Window {\n doNotTrack?: string | null;\n __NEXT_DATA__?: {\n buildId?: string;\n };\n}\n\nexport interface TrustedTypePolicyLike {\n createScriptURL(url: string): string;\n createScript(script: string): string;\n}\n\nexport interface WindowWithTrustedTypes extends Window {\n trustedTypes?: {\n createPolicy(\n name: string,\n rules: {\n createScriptURL?: (url: string) => string;\n createScript?: (script: string) => string;\n }\n ): TrustedTypePolicyLike;\n };\n}\n\nexport interface PerformanceMemoryInfo {\n usedJSHeapSize: number;\n totalJSHeapSize: number;\n jsHeapSizeLimit: number;\n}\n\nexport interface PerformanceWithMemory extends Performance {\n memory?: PerformanceMemoryInfo;\n measureUserAgentSpecificMemory?: () => Promise<unknown>;\n}\n\nexport interface LargestContentfulPaintEntry extends PerformanceEntry {\n renderTime?: number;\n loadTime?: number;\n}\n\n// ============================================================================\n// BEACON CONFIGURATION\n// ============================================================================\n\n/**\n * Who the current visitor is, when the host site knows.\n *\n * Deliberately just the id. The pixel's `identify` call also carries\n * `previousId` and `userTraits`, but those drive the server's profile and\n * alias-graph pipeline (tenant salt, profile-copy, write advisory locks),\n * which the beacon ingest route does not run — accepting them here would mean\n * collecting personal data the beacon path then silently discards. Both are\n * additive later: this is an optional field on an optional object.\n */\nexport interface BeaconIdentity {\n /**\n * The host site's own id for the signed-in user. Capped at 255 characters\n * to match `detections.user_id`; a longer value is rejected at ingest.\n */\n userId: string;\n}\n\n/** The beacon's automatic sends, each switchable off. See `BeaconConfig.triggers`. */\nexport interface BeaconDispatchTriggers {\n /** The `pageview` at construction and on consent restore. */\n arrival?: boolean;\n /** The follow-up send when the lazy signals chunk resolves after arrival missed it. */\n signals?: boolean;\n /** First interaction, first timing sample, and evidence growth. */\n interaction?: boolean;\n /** The first script-dispatched (untrusted) input. */\n untrusted?: boolean;\n /** An interaction after the posture token has gone stale. */\n posture?: boolean;\n /** The SDK-wired `visibilitychange` and `pagehide` critical send. */\n unload?: boolean;\n}\n\nexport interface BeaconConfig {\n /** Project ID for tracking (same as pixel data-project-id) */\n projectId: string;\n\n /**\n * Who the visitor is, when the page already knows at construction time.\n * When identity only becomes known later (a login part-way through the\n * session), call `identify()` instead.\n */\n identity?: BeaconIdentity;\n\n /**\n * Where batches are POSTed. Defaults to the hosted ingest endpoint declared\n * in `NETWORK_CONTRACT.md`.\n *\n * Set it to send somewhere else — a self-hosted deployment, a regional\n * install, or a test origin. An override means the destination is the\n * integrator's, not ours, so `NETWORK_CONTRACT.md` describes the DEFAULT and\n * says so explicitly.\n *\n * @default 'https://kya.vouched.id/api/v1/beacon'\n */\n endpoint?: string;\n\n /** Optional environment tag for data segmentation */\n environment?: 'development' | 'staging' | 'production' | string;\n\n /** Optional tags for custom data segmentation */\n tags?: Record<string, string | number | boolean>;\n\n /**\n * Not read by the SDK. Construct the beacon only when it should run, and\n * call `destroy()` to stop it.\n *\n * @deprecated\n */\n enabled?: boolean;\n\n /**\n * Verbose console logging.\n *\n * @default false\n */\n debug?: boolean;\n\n /**\n * Log verbosity.\n *\n * @default 'error'\n */\n logLevel?: 'error' | 'warn' | 'info' | 'debug';\n\n /**\n * When the browser sends Do Not Track, the beacon collects and sends nothing.\n *\n * @default true\n */\n respectDoNotTrack?: boolean;\n\n /**\n * Truncate the stored IP to /24 (IPv4) or /48 (IPv6) before persistence.\n * Read once at construction, so `updateConfig` will not change it; build a\n * new beacon instead.\n *\n * @default false\n */\n anonymizeIp?: boolean;\n\n /**\n * Strip the `#fragment` from the `url`/`referrer` collector fields before\n * they leave the page. Defaults to `true`: a fragment is never sent to\n * the server by the browser in the first place for any OTHER surface\n * (it is script-visible only), so a beacon that forwards it is the one\n * place it can leak — and it is also the highest-risk part of the URL,\n * since SPA routers, magic-link auth, and OAuth implicit-flow responses\n * all put tokens there. Set to `false` only if a project genuinely\n * consumes `url`'s fragment server-side.\n *\n * @default true\n */\n stripUrlFragment?: boolean;\n\n /**\n * Query parameter names (matched case-insensitively) to redact from the\n * `url`/`referrer` collector fields before they leave the page. Each\n * matching value is replaced with the literal string `\"[redacted]\"`; the\n * parameter itself stays present so the URL's shape is unchanged. Empty\n * by default — nothing is scrubbed unless a project opts in with the\n * param names it puts tokens/PII behind (e.g. `[\"token\", \"email\"]`).\n * Ignored for a parameter when `dropQueryParams` is also `true`, since\n * there is no query string left to scrub.\n *\n * @default []\n */\n scrubQueryParams?: string[];\n\n /**\n * Drop the entire query string from the `url`/`referrer` collector\n * fields before they leave the page. Off by default. Takes priority over\n * `scrubQueryParams` when both are set — there is nothing left to scrub\n * once the whole query string is gone.\n *\n * @default false\n */\n dropQueryParams?: boolean;\n\n /**\n * Inactivity timeout in milliseconds (30 minutes). Every send extends it,\n * so the session cookie rotates only after that much idle time.\n *\n * @default 1800000\n */\n sessionTimeout?: number;\n\n /**\n * Name of the visitor session cookie shared by pixel, beacon, gateway, and\n * SDK rows. Query it with `?sessionId=` on the\n * [detections endpoint](/docs/api-reference#get-project-detections).\n *\n * @default '_as_beacon_session'\n */\n sessionCookieName?: string;\n\n /**\n * @deprecated The beacon no longer batches; every dispatch sends\n * immediately. Accepted and ignored so a caller upgrading from an older\n * SDK version keeps compiling and does not need to touch its config.\n */\n batchSize?: number;\n\n /**\n * @deprecated The beacon no longer polls on an interval; it dispatches on\n * evidence transitions instead (arrival, first interaction, evidence\n * doubling, untrusted input, posture staleness, hidden/pagehide). Accepted\n * and ignored so a caller upgrading from an older SDK version keeps\n * compiling and does not need to touch its config.\n */\n flushInterval?: number;\n\n /**\n * How much `keyDwellCount + pressCount + untrustedEvents` has to grow, as a\n * multiple of its value at the last send, before an interaction sends\n * again. 2 sends at 1, 2, 4, 8, 16 samples; 1.5 sends more often, 3 less.\n * A value at or below 1 falls back to the default.\n *\n * @default 2\n */\n evidenceGrowthFactor?: number;\n\n /**\n * Fraction of the posture token's lifetime after which a counted\n * interaction sends again, so the token stays fresh under a live hand.\n * 0.5 refreshes the 120 s token once an interaction lands more than 60 s\n * after the last send. A value outside (0, 1] falls back to the default.\n *\n * @default 0.5\n */\n postureRefreshFraction?: number;\n\n /**\n * Which automatic sends fire. Every trigger is on unless set to `false`.\n * Turning `unload` off leaves `trackPageUnload()` available for a host\n * that wires its own listener; turning `arrival` off leaves `collect()`.\n */\n triggers?: BeaconDispatchTriggers;\n\n /**\n * Low-frequency backstop that refreshes posture on a jittered timer,\n * independent of interaction, so a visitor who goes idle past the posture\n * TTL with no counted interaction is not one stale click on a critical\n * action away from an expired token (H0BB5, PR #5095 review). The actual\n * interval on each tick is `proactiveRefreshMinIntervalMs` plus a random\n * `[0, max - min)` jitter, so a fleet of clients loaded at the same moment\n * does not all refresh on the same wall-clock boundary. Paused while the\n * page is hidden, resumed on `visibilitychange`. Gated by\n * `triggers.posture`, the same switch that already turns off the\n * interaction-triggered staleness check — this timer is that same\n * `'posture'` trigger firing proactively, not a second mechanism. A\n * non-positive value falls back to the default.\n *\n * @default 30000\n */\n proactiveRefreshMinIntervalMs?: number;\n\n /**\n * The upper bound of the proactive-refresh jitter window; see\n * `proactiveRefreshMinIntervalMs`. A non-positive value falls back to the\n * default; a value below `proactiveRefreshMinIntervalMs` degrades to the\n * minimum on every tick rather than throwing.\n *\n * @default 60000\n */\n proactiveRefreshMaxIntervalMs?: number;\n\n /**\n * How old the last send must be, in milliseconds, before a visibility\n * resume forces an immediate posture refresh. Defaults to the same\n * threshold the interaction-triggered check already uses\n * (`postureRefreshFraction` of the posture token's lifetime), so the two\n * stay in lockstep unless a host deliberately wants the visibility check\n * to be stricter or looser. A non-positive value falls back to that\n * default.\n */\n proactiveRefreshFreshnessMs?: number;\n\n /**\n * On `visibilitychange` back to visible, force an immediate posture\n * refresh when it is stale (see `proactiveRefreshFreshnessMs`); a fresh\n * tab regaining focus does not get an unnecessary send either way. Set to\n * `false` to leave visibility resume to the plain interval alone.\n *\n * @default true\n */\n proactiveRefreshOnVisibilityResume?: boolean;\n\n /**\n * Refresh posture (and drain anything the offline queue is still holding)\n * when the browser fires `online`. Set to `false` to leave reconnection\n * recovery to the offline queue's own `online` listener alone.\n *\n * @default true\n */\n proactiveRefreshOnOnline?: boolean;\n\n /**\n * A fixed seed for the proactive-refresh jitter roll, for deterministic\n * tests. Omit in production for real `Math.random()` jitter.\n */\n proactiveRefreshJitterSeed?: number;\n\n /**\n * Per-collector deadline in milliseconds. A collector still running past\n * this deadline is dropped from the current collection round rather than\n * awaited further — see `collectWithDeadline` in checkpoint-beacon.\n * Default and rationale documented in checkpoint-beacon's\n * `src/budget/thresholds.ts`.\n *\n * @default 1600\n */\n collectorDeadlineMs?: number;\n\n /**\n * Maximum number of queued events.\n *\n * @default 100\n */\n maxQueueSize?: number;\n\n /**\n * Retry count for failed sends.\n *\n * @default 3\n */\n retryAttempts?: number;\n\n /**\n * Base retry delay in milliseconds.\n *\n * @default 2000\n */\n retryDelay?: number;\n\n /**\n * Delays in milliseconds between posture-recovery attempts after a\n * durably-queued ingest response that carried no posture verdict. The\n * array's length is the attempt ceiling. Defaults to the shipped ladder;\n * override only in tests and in a self-hosted deployment with a\n * different outage profile.\n */\n postureRetryScheduleMs?: number[];\n\n /**\n * Prefer a Web Worker for event processing, batching, and transport.\n * Page-dependent collection remains on the main thread. Unsupported\n * browsers fall back to the main thread; SSR never starts a worker.\n * Set false to disable the processing worker.\n *\n * @default true\n */\n useWorker?: boolean;\n\n /**\n * Alias for `useWorker`, accepted for callers using the older option\n * name. When both are set, `useWorker` wins — see `resolveUseWorker`.\n */\n enableWebWorker?: boolean;\n\n /**\n * URL of the worker script (`beacon.worker.js`, exported as\n * `@kya-os/checkpoint-beacon/worker`). Classic workers must be same-origin.\n * When unset, the beacon derives `beacon.worker.js` next to the `<script>`\n * tag that loaded `beacon.min.js`, else `/beacon.worker.js` at the site root.\n */\n workerUrl?: string;\n\n /**\n * Worker lifecycle tuning: `initTimeoutMs` (3000), `messageTimeout` (30000),\n * `heartbeatInterval` (5000), `maxRetries` (3), `retryDelay` (1000),\n * `compressionThreshold` (5120), `allowFallback` (true).\n */\n workerConfig?: WorkerConfig;\n\n /**\n * Explicit URL override for the lazy-loaded signals chunk\n * (`beacon-lazy-signals.min.js` — userAgentData, fontPreferences, Client\n * Hints, webrtcCodecs, speechVoices, plus canvas/WebGL/audio/permissions\n * render entropy). Same shape and purpose as `workerUrl`: when unset,\n * checkpoint-beacon derives the chunk's URL from wherever `beacon.min.js`\n * itself was loaded from — see `checkpoint-beacon`'s\n * `src/core/load-lazy-chunk.ts` for the full resolution order.\n */\n lazySignalsUrl?: string;\n}\n\n// ============================================================================\n// BEACON EVENTS\n// ============================================================================\n\nexport interface BeaconEvent {\n /** Event type identifier */\n type: BeaconEventType;\n\n /** Event data payload */\n data: BeaconCollectorData;\n\n /** Event metadata */\n metadata: BeaconMetadata;\n}\n\nexport interface BeaconMetadata {\n /** Session ID */\n sessionId: string;\n\n /** Event timestamp */\n timestamp: number;\n\n /** Optional event name */\n eventName?: string;\n\n /** Present only once the host site has told us who the visitor is. */\n identity?: BeaconIdentity;\n\n /** Allow additional metadata */\n [key: string]: unknown;\n}\n\n// ============================================================================\n// BEACON API\n// ============================================================================\n\nexport interface IAgentShieldBeacon {\n /**\n * Collect a generic event\n */\n collect(eventType: string, data?: BeaconPayload): Promise<void>;\n\n /**\n * Track a custom event\n */\n trackEvent(eventName: string, eventData?: BeaconPayload): Promise<void>;\n\n /**\n * Track a pageview\n */\n trackPageview(pageData?: BeaconPayload): Promise<void>;\n\n /**\n * Track page unload\n */\n trackPageUnload(): Promise<void>;\n\n /**\n * Update configuration\n */\n updateConfig(updates: Partial<BeaconConfig>): void;\n\n /**\n * Destroy the beacon and clean up\n */\n destroy(): Promise<void>;\n}\n\n// ============================================================================\n// RESPONSE TYPES\n// ============================================================================\n\nexport interface BeaconResponse {\n /** Response status */\n status: 'success' | 'error';\n\n /** Optional message */\n message?: string;\n\n /** Optional error details */\n error?: {\n code: string;\n message: string;\n };\n}\n\n// ============================================================================\n// BROWSER CONTEXT\n// ============================================================================\n\nexport interface BrowserContext {\n /** Browser name and version */\n browser: {\n name: string;\n version: string;\n engine: string;\n };\n\n /** Operating system */\n os: {\n name: string;\n version: string;\n };\n\n /** Device information */\n device: {\n type: 'desktop' | 'mobile' | 'tablet' | 'tv' | 'unknown';\n vendor?: string;\n model?: string;\n };\n\n /** Screen information */\n screen: {\n width: number;\n height: number;\n pixelRatio: number;\n colorDepth: number;\n };\n\n /** Connection information */\n connection?: {\n type: 'bluetooth' | 'cellular' | 'ethernet' | 'none' | 'wifi' | 'wimax' | 'other' | 'unknown';\n effectiveType?: '2g' | '3g' | '4g' | '5g';\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n };\n}\n\n// ============================================================================\n// PERFORMANCE METRICS\n// ============================================================================\n\nexport interface PerformanceMetrics {\n /** Page load time in milliseconds */\n pageLoadTime?: number;\n\n /** DOM content loaded time */\n domContentLoadedTime?: number;\n\n /** Time to interactive */\n timeToInteractive?: number;\n\n /** First paint time */\n firstPaintTime?: number;\n\n /** First contentful paint time */\n firstContentfulPaintTime?: number;\n\n /** Largest contentful paint time */\n largestContentfulPaintTime?: number;\n\n /** DNS lookup time */\n dnsLookupTime?: number;\n\n /** TCP connection time */\n tcpConnectionTime?: number;\n\n /** Server response time */\n serverResponseTime?: number;\n\n /** Resource timing */\n resources?: {\n scripts: number;\n stylesheets: number;\n images: number;\n fonts: number;\n total: number;\n };\n}\n\n// ============================================================================\n// SESSION TYPES\n// ============================================================================\n\nexport interface SessionData {\n /** Unique session ID */\n id: string;\n\n /** Session start timestamp */\n startTime: number;\n\n /** Last activity timestamp */\n lastActivity: number;\n\n /** Page view count in session */\n pageViews: number;\n\n /** Event count in session */\n eventCount: number;\n\n /** Session duration in milliseconds */\n duration: number;\n\n /** Is this a new session */\n isNew: boolean;\n}\n\n// ============================================================================\n// TRANSPORT TYPES\n// ============================================================================\n\nexport interface TransportConfig {\n maxRetries: number;\n retryDelayBase: number;\n offlineQueueSize: number;\n useCompression: boolean;\n compressionThreshold: number;\n /** Build item 6: carried onto every outgoing `BeaconBatch` — see `BeaconConfig.anonymizeIp`. */\n anonymizeIp?: boolean;\n}\n\nexport interface TransportOptions {\n immediate?: boolean;\n priority?: 'low' | 'normal' | 'high' | 'critical';\n retry?: boolean;\n timeout?: number;\n}\n\nexport interface TransportResponse {\n success: boolean;\n timestamp: number;\n batchId?: string;\n error?: string;\n}\n\nexport type TransportState = 'idle' | 'sending' | 'offline' | 'paused' | 'error';\n\nexport interface TransportMetrics {\n eventsSent: number;\n eventsFailed: number;\n eventsQueued: number;\n batchesSent: number;\n batchesFailed: number;\n bytesTransferred: number;\n compressionRatio?: number;\n averageLatency?: number;\n lastSuccessTimestamp?: number;\n lastErrorTimestamp?: number;\n}\n\nexport type ConnectionType =\n | 'bluetooth'\n | 'cellular'\n | 'ethernet'\n | 'none'\n | 'wifi'\n | 'wimax'\n | 'other'\n | 'unknown';\n\nexport interface NetworkInfo {\n type?: string;\n effectiveType?: string;\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n}\n\n// ============================================================================\n// WORKER TYPES\n// ============================================================================\n\nexport type MessagePriority = 'low' | 'normal' | 'high' | 'critical';\nexport type WorkerErrorType =\n | 'initialization'\n | 'runtime'\n | 'communication'\n | 'timeout'\n | 'memory'\n | 'network'\n | 'permission'\n | 'validation'\n | 'processing'\n | 'unknown';\nexport type WorkerAction =\n | 'process'\n | 'init'\n | 'terminate'\n | 'pause'\n | 'resume'\n | 'status'\n | 'health';\nexport type WorkerMessageType = 'request' | 'response' | 'error' | 'heartbeat' | 'status';\n\nexport interface WorkerMessage {\n id: string;\n type: 'request' | 'response' | 'error' | 'heartbeat' | 'status';\n action?: string;\n payload?: WorkerPayload;\n timestamp: number;\n compressed?: boolean;\n priority?: MessagePriority;\n correlationId?: string;\n}\n\nexport type WorkerState =\n | 'idle'\n | 'initializing'\n | 'ready'\n | 'processing'\n | 'busy'\n | 'error'\n | 'terminating'\n | 'terminated';\n\nexport type WorkerHealthStatus = 'healthy' | 'degraded' | 'unhealthy' | 'unknown';\n\nexport interface WorkerMetrics {\n tasksProcessed: number;\n tasksFailed: number;\n averageProcessingTime?: number;\n memoryUsage?: number;\n cpuUsage?: number;\n healthStatus: WorkerHealthStatus;\n lastHealthCheck: number;\n restartCount: number;\n errorRate?: number;\n errorCount: number;\n messageQueueSize: number;\n startTime: number;\n uptime: number;\n averageTaskTime?: number;\n lastTaskTime?: number;\n}\n\nexport interface WorkerError {\n type: WorkerErrorType;\n code?: string;\n message: string;\n stack?: string;\n timestamp: number;\n recoverable: boolean;\n retryAfter?: number;\n context?: Record<string, unknown>;\n}\n\nexport interface WorkerCapabilities {\n workerAPI: boolean;\n sharedArrayBuffer: boolean;\n transferableObjects: boolean;\n offscreenCanvas: boolean;\n webAssembly: boolean;\n atomics: boolean;\n bigInt: boolean;\n csp: {\n workerSrc: boolean;\n scriptSrc: boolean;\n blobUrls: boolean;\n inlineWorkers: boolean;\n };\n performance: {\n memory: boolean;\n measureUserAgentSpecificMemory: boolean;\n };\n}\n\nexport interface WorkerTask {\n id: string;\n type: string;\n data: WorkerPayload;\n priority: 'low' | 'normal' | 'high' | 'critical';\n createdAt: number;\n startedAt?: number;\n completedAt?: number;\n error?: WorkerError;\n maxRetries?: number;\n retries?: number;\n timeout?: number;\n}\n\nexport interface FallbackOptions {\n useRequestIdleCallback: boolean;\n idleTimeout: number;\n chunkSize: number;\n throttleMs: number;\n maxExecutionTime: number;\n}\n\nexport interface ResourceUsage {\n memory: {\n used: number;\n limit: number;\n percentage: number;\n };\n cpu: {\n usage: number;\n limit: number;\n };\n tasks: {\n pending: number;\n active: number;\n completed: number;\n failed: number;\n };\n activeWorkers: number;\n}\n\nexport interface WorkerPoolConfig {\n maxWorkers: number;\n minWorkers: number;\n workerIdleTimeout: number;\n taskQueueSize: number;\n resourceLimits: Record<string, number>;\n autoScale?: boolean;\n scaleUpThreshold?: number;\n scaleDownThreshold?: number;\n}\n\nexport type BeaconWorkerMessageType =\n | 'init'\n | 'collect'\n | 'flush'\n | 'config'\n | 'status'\n | 'error'\n | 'response'\n // Unsolicited worker -> main relay of a 202 ingest body (posture cookie\n // delivery needs `document`, which the worker lacks).\n | 'posture';\nexport type ProtocolVersion = '1.0' | '1.1' | '2.0';\n\nexport interface BeaconWorkerMessage {\n type: BeaconWorkerMessageType;\n data?: WorkerPayload;\n payload?: WorkerPayload;\n messageId: string;\n timestamp: number;\n id: string;\n}\n\nexport interface WorkerConfig {\n enabled?: boolean;\n url?: string;\n heartbeatInterval?: number;\n maxUnhealthyCount?: number;\n maxRetries?: number;\n retryDelay?: number;\n restartDelay?: number;\n messageTimeout?: number;\n compressionThreshold?: number;\n allowFallback?: boolean;\n crossOriginIsolated?: boolean;\n maxRestartAttempts?: number;\n terminationTimeout?: number;\n taskTimeout?: number;\n fallbackDelay?: number;\n enableFallback?: boolean;\n /**\n * Hard ceiling on how long worker startup (script load + init handshake)\n * gets before the caller gives up and falls back to the main-thread\n * transport. Deliberately separate from `taskTimeout`/`messageTimeout`\n * (which govern steady-state message round trips once the worker is\n * already up): a slow or hung worker script would otherwise hold up\n * every event for the full 30s message timeout before anything left the\n * page. A few seconds is enough for a healthy worker to load and answer\n * its init message; anything slower isn't worth waiting on.\n */\n initTimeoutMs?: number;\n}\n\n// ============================================================================\n// CIRCUIT BREAKER & RETRY\n// ============================================================================\n\nexport interface CircuitBreakerConfig {\n threshold: number;\n timeout: number;\n resetTimeout: number;\n}\n\nexport type CircuitBreakerState = 'closed' | 'open' | 'half-open';\n\nexport interface RetryStrategy {\n maxAttempts: number;\n baseDelay: number;\n maxDelay: number;\n factor: number;\n jitter: boolean;\n}\n\n// ============================================================================\n// OFFLINE QUEUE\n// ============================================================================\n\nexport interface OfflineQueueEntry {\n id: string;\n events: BeaconEvent[];\n timestamp: number;\n expiresAt: number;\n retryCount: number;\n size: number;\n}\n\n// ============================================================================\n// BEACON BATCH\n// ============================================================================\n\nexport interface BeaconBatch {\n projectId: string;\n events: BeaconEvent[];\n sessionId: string;\n batchId: string;\n timestamp: number;\n /** Build item 6: mirrors `BeaconConfig.anonymizeIp` (default `false`) — see the beacon route's own doc comment. */\n anonymizeIp?: boolean;\n /** Nonce-bound ingest (build item 5): the value from the prior 202 response's `nonce`. */\n nonce?: string;\n /** Nonce-bound ingest (build item 5): declares this client echoes nonces — see checkpoint-beacon's `BeaconBatch`. */\n nonceEcho?: boolean;\n}\n\nexport interface BeaconCollectorData {\n // Browser collector data\n userAgent?: string;\n language?: string;\n platform?: string;\n screenResolution?: string;\n viewport?: string;\n cookiesEnabled?: boolean;\n doNotTrack?: boolean;\n timezone?: string;\n referrer?: string;\n url?: string;\n title?: string;\n vendor?: string;\n\n // Performance collector data\n pageLoadTime?: number;\n domContentLoadedTime?: number;\n firstPaintTime?: number;\n firstContentfulPaintTime?: number;\n connectionType?: string;\n\n // Session data\n sessionId?: string;\n timestamp?: number;\n\n // Allow additional properties\n [key: string]: unknown;\n}\n\nexport type BeaconEventType =\n | 'pageview'\n | 'pageunload'\n | 'heartbeat'\n | 'evidence'\n | 'custom'\n | 'error'\n | 'performance';\n\n// ============================================================================\n// PARSER FUNCTIONS\n// ============================================================================\n\nexport function parseRetryStrategy(input: unknown): RetryStrategy {\n const strategy = toRecord(input);\n return {\n maxAttempts: numberOr(strategy.maxAttempts, 3),\n baseDelay: numberOr(strategy.baseDelay, 1000),\n maxDelay: numberOr(strategy.maxDelay, 30000),\n factor: numberOr(strategy.factor, 2),\n jitter: strategy.jitter !== false,\n };\n}\n\nexport function parseCircuitBreakerConfig(input: unknown): CircuitBreakerConfig {\n const config = toRecord(input);\n return {\n threshold: numberOr(config.threshold, 5),\n timeout: numberOr(config.timeout, 60000),\n resetTimeout: numberOr(config.resetTimeout, 30000),\n };\n}\n\nexport function parseOfflineQueueEntry(input: unknown): OfflineQueueEntry {\n if (!isRecord(input)) {\n throw new Error('Invalid offline queue entry');\n }\n\n const entry = input;\n return {\n id: stringOr(entry.id, `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`)!,\n events: Array.isArray(entry.events) ? (entry.events as BeaconEvent[]) : [],\n timestamp: numberOr(entry.timestamp, Date.now()),\n expiresAt: numberOr(entry.expiresAt, Date.now() + 86400000), // 24 hours\n retryCount: numberOr(entry.retryCount, 0),\n size: numberOr(entry.size, 0),\n };\n}\n\nexport function parseBeaconWorkerMessage(input: unknown): BeaconWorkerMessage {\n if (!isRecord(input)) {\n throw new Error('Invalid beacon worker message');\n }\n\n const msg = input;\n const messageId = stringOr(msg.messageId) ?? stringOr(msg.id) ?? crypto.randomUUID();\n return {\n type: isBeaconWorkerMessageType(msg.type) ? msg.type : 'init',\n data: msg.data,\n payload: msg.payload,\n messageId,\n timestamp: numberOr(msg.timestamp, Date.now()),\n id: stringOr(msg.id, messageId)!,\n };\n}\n\nfunction isMessagePriority(value: unknown): value is MessagePriority {\n return value === 'low' || value === 'normal' || value === 'high' || value === 'critical';\n}\n\nfunction isWorkerMessageType(value: unknown): value is WorkerMessageType {\n return (\n value === 'request' ||\n value === 'response' ||\n value === 'error' ||\n value === 'heartbeat' ||\n value === 'status'\n );\n}\n\nfunction isWorkerErrorType(value: unknown): value is WorkerErrorType {\n return (\n value === 'initialization' ||\n value === 'runtime' ||\n value === 'communication' ||\n value === 'timeout' ||\n value === 'memory' ||\n value === 'network' ||\n value === 'permission' ||\n value === 'validation' ||\n value === 'processing' ||\n value === 'unknown'\n );\n}\n\nexport function parseWorkerMessage(input: unknown): WorkerMessage {\n const msg = (input && typeof input === 'object' ? input : null) as Partial<WorkerMessage> | null;\n if (!msg) {\n throw new Error('Invalid worker message');\n }\n\n return {\n id: msg.id || crypto.randomUUID(),\n type: isWorkerMessageType(msg.type) ? msg.type : 'request',\n action: msg.action,\n payload: msg.payload,\n timestamp: msg.timestamp || Date.now(),\n compressed: msg.compressed,\n priority: isMessagePriority(msg.priority) ? msg.priority : 'normal',\n correlationId: msg.correlationId,\n };\n}\n\nexport function parseWorkerError(input: unknown): WorkerError {\n const error = (input && typeof input === 'object' ? input : {}) as Partial<WorkerError>;\n return {\n type: isWorkerErrorType(error.type) ? error.type : 'unknown',\n code: typeof error.code === 'string' ? error.code : undefined,\n message: typeof error.message === 'string' ? error.message : 'Worker error',\n stack: typeof error.stack === 'string' ? error.stack : undefined,\n timestamp: typeof error.timestamp === 'number' ? error.timestamp : Date.now(),\n recoverable: error.recoverable !== false,\n retryAfter: typeof error.retryAfter === 'number' ? error.retryAfter : undefined,\n context: error.context,\n };\n}\n\nexport function parseWorkerPoolConfig(input: unknown): WorkerPoolConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Partial<WorkerPoolConfig>;\n return {\n maxWorkers: config.maxWorkers ?? 4,\n minWorkers: config.minWorkers ?? 1,\n workerIdleTimeout: config.workerIdleTimeout ?? 30000,\n taskQueueSize: config.taskQueueSize ?? 100,\n resourceLimits: config.resourceLimits ?? {},\n autoScale: config.autoScale ?? true,\n scaleUpThreshold: config.scaleUpThreshold ?? 75,\n scaleDownThreshold: config.scaleDownThreshold ?? 25,\n };\n}\n\nexport function parseResourceUsage(input: unknown): ResourceUsage {\n const usage = (input && typeof input === 'object' ? input : {}) as Partial<ResourceUsage>;\n return {\n memory: usage.memory ?? { used: 0, limit: 0, percentage: 0 },\n cpu: usage.cpu ?? { usage: 0, limit: 100 },\n tasks: usage.tasks ?? { pending: 0, active: 0, completed: 0, failed: 0 },\n activeWorkers: usage.activeWorkers ?? 0,\n };\n}\n\nexport const ResourceUsageSchema = {\n parse: parseResourceUsage,\n};\n\nexport const WorkerPoolConfigSchema = {\n parse: parseWorkerPoolConfig,\n};\n\nexport function parseWorkerCapabilities(input: unknown): WorkerCapabilities {\n const cap = toRecord(input);\n const csp = toRecord(cap.csp);\n const performance = toRecord(cap.performance);\n\n return {\n workerAPI: cap.workerAPI !== false,\n sharedArrayBuffer: cap.sharedArrayBuffer === true,\n transferableObjects: cap.transferableObjects === true,\n offscreenCanvas: cap.offscreenCanvas === true,\n webAssembly: cap.webAssembly === true,\n atomics: cap.atomics === true,\n bigInt: cap.bigInt === true,\n csp: {\n workerSrc: csp.workerSrc === true,\n scriptSrc: csp.scriptSrc === true,\n blobUrls: csp.blobUrls === true,\n inlineWorkers: csp.inlineWorkers === true,\n },\n performance: {\n memory: performance.memory === true,\n measureUserAgentSpecificMemory: performance.measureUserAgentSpecificMemory === true,\n },\n };\n}\n\n/**\n * @param onWarn Called once per rejected config value (a supplied value that\n * failed validation and fell back to its default), for a caller that wants\n * to surface it — `BeaconConfigManager.validateAndMergeConfig` wires this to\n * `log('warn', ...)`. Never called for an omitted field; only for one the\n * caller actually set to something invalid.\n */\nexport function parseBeaconConfig(\n input: unknown,\n onWarn?: (message: string) => void\n): BeaconConfig {\n const config = toRecord(input);\n\n if (typeof config.projectId !== 'string' || config.projectId.length === 0) {\n throw new Error('Project ID is required');\n }\n\n return {\n projectId: config.projectId,\n environment: stringOr(config.environment),\n tags: isBeaconTags(config.tags) ? config.tags : undefined,\n identity: isBeaconIdentity(config.identity) ? config.identity : undefined,\n // `parseBeaconConfig` is an allowlist: a key it does not name is dropped\n // silently, which is how `identity` first shipped inert.\n endpoint: stringOr(config.endpoint),\n enabled: config.enabled !== false,\n debug: config.debug === true,\n logLevel: isLogLevel(config.logLevel) ? config.logLevel : 'error',\n respectDoNotTrack: config.respectDoNotTrack !== false,\n anonymizeIp: config.anonymizeIp === true,\n stripUrlFragment: config.stripUrlFragment !== false,\n scrubQueryParams: isStringArray(config.scrubQueryParams) ? config.scrubQueryParams : undefined,\n dropQueryParams: config.dropQueryParams === true,\n sessionTimeout: numberOr(config.sessionTimeout, 1800000), // 30 minutes\n sessionCookieName: stringOr(config.sessionCookieName, '_as_beacon_session'),\n // Deprecated no-ops (see BeaconConfig.batchSize/flushInterval): passed\n // through when a caller sets them so a stale value round-trips through\n // `get()`, never defaulted, since nothing reads them anymore.\n batchSize: typeof config.batchSize === 'number' ? config.batchSize : undefined,\n flushInterval: typeof config.flushInterval === 'number' ? config.flushInterval : undefined,\n // 1600ms — see packages/checkpoint-beacon/src/budget/thresholds.ts\n // (MAX_PER_SOURCE_DEADLINE_MS) for the full measurement-backed rationale;\n // sized to sit just above the vendored FingerprintJS pipeline's own\n // already-ratified 1500ms TOTAL_COLLECTION_BUDGET_MS\n // (collectors/entropy/vendored-fingerprint.ts), so a future collector\n // wrapping that pipeline gets to use its own internal timeout instead\n // of being truncated one layer up before it fires. Keep these two\n // literals in sync; checkpoint-shared can't import from\n // checkpoint-beacon (wrong direction of the package dependency graph).\n collectorDeadlineMs: numberOr(config.collectorDeadlineMs, 1600),\n evidenceGrowthFactor: boundedNumberOr(\n config.evidenceGrowthFactor,\n 2,\n (n) => n > 1,\n (received) =>\n onWarn?.(\n `evidenceGrowthFactor must be a number greater than 1 (received ${JSON.stringify(received)}); using default 2`\n )\n ),\n postureRefreshFraction: boundedNumberOr(\n config.postureRefreshFraction,\n 0.5,\n (n) => n > 0 && n <= 1,\n (received) =>\n onWarn?.(\n `postureRefreshFraction must be a number in (0, 1] (received ${JSON.stringify(received)}); using default 0.5`\n )\n ),\n triggers: pickTriggers(config.triggers, (name, received) =>\n onWarn?.(\n `triggers.${name} must be a boolean (received ${JSON.stringify(received)}); ignoring it and keeping its default`\n )\n ),\n maxQueueSize: numberOr(config.maxQueueSize, 100),\n retryAttempts: numberOr(config.retryAttempts, 3),\n retryDelay: numberOr(config.retryDelay, 2000),\n postureRetryScheduleMs: isPositiveNumberArray(config.postureRetryScheduleMs)\n ? config.postureRetryScheduleMs\n : undefined,\n useWorker: resolveUseWorker(config),\n workerUrl: stringOr(config.workerUrl),\n workerConfig: isRecord(config.workerConfig) ? (config.workerConfig as WorkerConfig) : undefined,\n lazySignalsUrl: stringOr(config.lazySignalsUrl),\n proactiveRefreshMinIntervalMs: boundedNumberOr(\n config.proactiveRefreshMinIntervalMs,\n 30_000,\n (n) => n > 0,\n (received) =>\n onWarn?.(\n `proactiveRefreshMinIntervalMs must be a positive number (received ${JSON.stringify(received)}); using default 30000`\n )\n ),\n proactiveRefreshMaxIntervalMs: boundedNumberOr(\n config.proactiveRefreshMaxIntervalMs,\n 60_000,\n (n) => n > 0,\n (received) =>\n onWarn?.(\n `proactiveRefreshMaxIntervalMs must be a positive number (received ${JSON.stringify(received)}); using default 60000`\n )\n ),\n proactiveRefreshFreshnessMs: optionalPositiveNumber(\n config.proactiveRefreshFreshnessMs,\n (received) =>\n onWarn?.(\n `proactiveRefreshFreshnessMs must be a positive number (received ${JSON.stringify(received)}); ignoring it and inheriting postureRefreshFraction's threshold`\n )\n ),\n proactiveRefreshOnVisibilityResume: booleanOr(\n config.proactiveRefreshOnVisibilityResume,\n true,\n (received) =>\n onWarn?.(\n `proactiveRefreshOnVisibilityResume must be a boolean (received ${JSON.stringify(received)}); using default true`\n )\n ),\n proactiveRefreshOnOnline: booleanOr(config.proactiveRefreshOnOnline, true, (received) =>\n onWarn?.(\n `proactiveRefreshOnOnline must be a boolean (received ${JSON.stringify(received)}); using default true`\n )\n ),\n proactiveRefreshJitterSeed: optionalFiniteNumber(\n config.proactiveRefreshJitterSeed,\n (received) =>\n onWarn?.(\n `proactiveRefreshJitterSeed must be a finite number (received ${JSON.stringify(received)}); ignoring it, jitter will use Math.random()`\n )\n ),\n };\n}\n\n// ============================================================================\n// EXPORT MAIN CLASS TYPE\n// ============================================================================\n\nexport declare class AgentShieldBeacon implements IAgentShieldBeacon {\n constructor(config: BeaconConfig);\n collect(eventType: string, data?: BeaconPayload): Promise<void>;\n trackEvent(eventName: string, eventData?: BeaconPayload): Promise<void>;\n trackPageview(pageData?: BeaconPayload): Promise<void>;\n trackPageUnload(): Promise<void>;\n updateConfig(updates: Partial<BeaconConfig>): void;\n destroy(): Promise<void>;\n}\n\n// ============================================================================\n// WIRE LIMITS SHARED BY THE SDK AND THE INGEST ROUTE\n// ============================================================================\n\n/**\n * The most events one beacon POST may carry. The ingest route's\n * `BeaconBatchSchema` refuses a larger batch whole (a 400, not a retry), so\n * the SDK's offline drain never dequeues more than this per request.\n */\nexport const BEACON_MAX_EVENTS_PER_BATCH = 100;\n\n/**\n * Lifetime of the signed browser posture token, in seconds. Defined here and\n * re-exported by `browser-posture.ts` (which imports `jose`) so the\n * size-budgeted beacon bundle can read it without pulling in a JWT library.\n */\nexport const POSTURE_TTL_SECONDS = 120;\n"],"mappings":";AAgBA,SAAS,SAAS,OAAwC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU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SAAS,OAAO,SAAS;EACpC,cAAc,SAAS,OAAO,YAAY,IAAK,OAAO,eAAgC;EACtF,gBAAgB,SAAS,OAAO,cAAc;EAC9C,+BAA+B,gBAC7B,OAAO,+BACP,MACC,MAAM,IAAI,IACV,aACC,SACE,qEAAqE,KAAK,UAAU,QAAQ,EAAE,uBAChG,CACJ;EACA,+BAA+B,gBAC7B,OAAO,+BACP,MACC,MAAM,IAAI,IACV,aACC,SACE,qEAAqE,KAAK,UAAU,QAAQ,EAAE,uBAChG,CACJ;EACA,6BAA6B,uBAC3B,OAAO,8BACN,aACC,SACE,mEAAmE,KAAK,UAAU,QAAQ,EAAE,iEAC9F,CACJ;EACA,oCAAoC,UAClC,OAAO,oCACP,OACC,aACC,SACE,kEAAkE,KAAK,UAAU,QAAQ,EAAE,sBAC7F,CACJ;EACA,0BAA0B,UAAU,OAAO,0BAA0B,OAAO,aAC1E,SACE,wDAAwD,KAAK,UAAU,QAAQ,EAAE,sBACnF,CACF;EACA,4BAA4B,qBAC1B,OAAO,6BACN,aACC,SACE,gEAAgE,KAAK,UAAU,QAAQ,EAAE,8CAC3F,CACJ;CACF;AACF;;;;;;AAyBA,MAAa,8BAA8B;;;;;;AAO3C,MAAa,sBAAsB"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/beacon-types/index.ts"],"sourcesContent":["/**\n * Public TypeScript types for Checkpoint Beacon\n *\n * This package contains only the public API types needed by beacon consumers.\n * No implementation details or detection rules are included.\n */\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue | undefined };\nexport type BeaconPrimitive = JsonPrimitive;\nexport type BeaconJsonValue = JsonValue;\nexport type BeaconCustomData = Record<string, JsonValue | undefined>;\nexport type BeaconPayload = BeaconCollectorData | BeaconCustomData | null;\nexport type WorkerPayload = unknown;\ntype UnknownRecord = Record<string, unknown>;\n\nfunction isRecord(input: unknown): input is UnknownRecord {\n return typeof input === 'object' && input !== null && !Array.isArray(input);\n}\n\nfunction toRecord(input: unknown): UnknownRecord {\n return isRecord(input) ? input : {};\n}\n\nfunction numberOr<Fallback extends number | undefined>(\n value: unknown,\n fallback: Fallback\n): number | Fallback {\n return typeof value === 'number' && Number.isFinite(value) && value !== 0 ? value : fallback;\n}\n\n/**\n * Validates a numeric config value against `ok`, falling back to `fallback`\n * when it fails. Only calls `onReject` when the caller actually supplied a\n * value (an `undefined` field, the common case, is not a rejection, it just\n * never overrode the default): H0BB5 (PR #5095 review, item 4) — a rejected\n * value used to fall back silently, with no way for a host to discover a\n * config typo.\n */\nfunction boundedNumberOr(\n value: unknown,\n fallback: number,\n ok: (n: number) => boolean,\n onReject?: (received: unknown) => void\n): number {\n if (typeof value === 'number' && Number.isFinite(value) && ok(value)) return value;\n if (value !== undefined) onReject?.(value);\n return fallback;\n}\n\n/** Same as `boundedNumberOr`, but an absent/rejected value stays `undefined` rather than defaulting. */\nfunction optionalPositiveNumber(\n value: unknown,\n onReject?: (received: unknown) => void\n): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value;\n onReject?.(value);\n return undefined;\n}\n\n/** Same as `optionalPositiveNumber`, without the positivity requirement (a jitter seed may be any finite number). */\nfunction optionalFiniteNumber(\n value: unknown,\n onReject?: (received: unknown) => void\n): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n onReject?.(value);\n return undefined;\n}\n\n/** Same shape as `boundedNumberOr`/`optionalPositiveNumber`, for a boolean config flag. */\nfunction booleanOr(\n value: unknown,\n fallback: boolean,\n onReject?: (received: unknown) => void\n): boolean {\n if (value === undefined) return fallback;\n if (typeof value === 'boolean') return value;\n onReject?.(value);\n return fallback;\n}\n\n/** Ingest's own `sessionId` bound (1-255), limited to characters a cookie value carries unescaped. */\nconst RESUMABLE_SESSION_ID = /^[A-Za-z0-9._~-]{1,255}$/;\n\nfunction resumableSessionId(\n value: unknown,\n onReject?: (received: unknown) => void\n): string | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'string' && RESUMABLE_SESSION_ID.test(value)) return value;\n onReject?.(value);\n return undefined;\n}\n\nfunction receiptCallback(\n value: unknown,\n onReject?: (received: unknown) => void\n): BeaconConfig['onReceipt'] {\n if (value === undefined) return undefined;\n if (typeof value === 'function') return value as BeaconConfig['onReceipt'];\n onReject?.(value);\n return undefined;\n}\n\nconst DISPATCH_TRIGGER_NAMES = [\n 'arrival',\n 'signals',\n 'interaction',\n 'untrusted',\n 'posture',\n 'unload',\n 'navigation',\n] as const satisfies readonly (keyof BeaconDispatchTriggers)[];\n\n/**\n * Keeps only the known trigger names with a real boolean; anything else is\n * dropped and, when the caller actually named a known trigger with a\n * non-boolean value (`triggers: { posture: 0 }`, say), reported through\n * `onReject` — H0BB5 (PR #5095 review, item 4): a numeric `0` used to be\n * dropped silently and that trigger stayed at its default-enabled state,\n * the opposite of what the \"0 is falsy\" convention suggests.\n */\nfunction pickTriggers(\n value: unknown,\n onReject?: (name: string, received: unknown) => void\n): BeaconDispatchTriggers | undefined {\n if (!isRecord(value)) return undefined;\n const picked: BeaconDispatchTriggers = {};\n for (const name of DISPATCH_TRIGGER_NAMES) {\n const raw = value[name];\n if (typeof raw === 'boolean') {\n picked[name] = raw;\n } else if (raw !== undefined) {\n onReject?.(name, raw);\n }\n }\n return picked;\n}\n\nfunction stringOr(value: unknown, fallback?: string): string | undefined {\n return typeof value === 'string' ? value : fallback;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((entry) => typeof entry === 'string');\n}\n\n/**\n * Non-empty on purpose: an empty schedule would mean \"zero posture-recovery\n * attempts\", silently disabling recovery rather than configuring it. A\n * deployment that actually wants no retries sets `flushInterval` instead.\n */\nfunction isPositiveNumberArray(value: unknown): value is number[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every((entry) => typeof entry === 'number' && Number.isFinite(entry) && entry > 0)\n );\n}\n\nfunction isBeaconTags(value: unknown): value is Record<string, string | number | boolean> {\n return (\n isRecord(value) &&\n Object.values(value).every(\n (entry) =>\n typeof entry === 'string' || typeof entry === 'number' || typeof entry === 'boolean'\n )\n );\n}\n\n/**\n * Exported because `parseBeaconConfig` is an allowlist: a key it does not\n * name is dropped, silently. The beacon's other public entry point\n * (`checkpoint-shared/browser`) carries its own copy of that allowlist, so\n * the CHECK at least lives in one place even while the two parsers do not —\n * see the note on `BeaconConfig.identity`.\n *\n * Rejects an identity with no usable `userId` rather than passing through a\n * half-formed object: downstream this becomes `detections.user_id`, and an\n * empty string there is worse than an absent one — it reads as \"identified\"\n * while naming nobody.\n */\nexport function isBeaconIdentity(value: unknown): value is BeaconIdentity {\n return isRecord(value) && typeof value.userId === 'string' && value.userId.length > 0;\n}\n\nfunction isLogLevel(value: unknown): value is BeaconConfig['logLevel'] {\n return value === 'error' || value === 'warn' || value === 'info' || value === 'debug';\n}\n\nfunction isBeaconWorkerMessageType(value: unknown): value is BeaconWorkerMessageType {\n return (\n value === 'init' ||\n value === 'collect' ||\n value === 'flush' ||\n value === 'config' ||\n value === 'status' ||\n value === 'error' ||\n // `beacon.worker.ts`'s `respond()` has always sent this on every\n // successful request (init/collect/flush/config/status) — the allowlist\n // just never named it, so `parseBeaconWorkerMessage` silently coerced\n // every success response to `'init'` (see that function's fallback).\n value === 'response' ||\n value === 'posture'\n );\n}\n\n/**\n * Resolves whether a beacon should use its Web Worker transport.\n *\n * `enableWebWorker` is accepted as an alias for `useWorker`: the package's\n * own test suite (`checkpoint-beacon/src/index.test.ts`) has always\n * constructed with `enableWebWorker: false`, but `parseBeaconConfig`'s\n * allowlist only ever named `useWorker`, so that key was silently dropped —\n * the beacon kept auto-detecting worker support regardless of what the\n * caller passed. `useWorker` wins when both are set, since it's the\n * canonical name every other config field (`workerUrl`, `workerConfig`)\n * pairs with.\n */\nfunction resolveUseWorker(config: UnknownRecord): boolean {\n if (typeof config.useWorker === 'boolean') {\n return config.useWorker;\n }\n if (typeof config.enableWebWorker === 'boolean') {\n return config.enableWebWorker;\n }\n return true;\n}\n\nexport interface NetworkInformationLike extends EventTarget {\n type?: string;\n effectiveType?: string;\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n}\n\nexport interface NavigatorWithNetworkInformation extends Navigator {\n connection?: NetworkInformationLike;\n mozConnection?: NetworkInformationLike;\n webkitConnection?: NetworkInformationLike;\n deviceMemory?: number;\n vendorSub: string;\n doNotTrack: string | null;\n msDoNotTrack?: string | null;\n}\n\nexport interface WindowWithBeaconMetadata extends Window {\n doNotTrack?: string | null;\n __NEXT_DATA__?: {\n buildId?: string;\n };\n}\n\nexport interface TrustedTypePolicyLike {\n createScriptURL(url: string): string;\n createScript(script: string): string;\n}\n\nexport interface WindowWithTrustedTypes extends Window {\n trustedTypes?: {\n createPolicy(\n name: string,\n rules: {\n createScriptURL?: (url: string) => string;\n createScript?: (script: string) => string;\n }\n ): TrustedTypePolicyLike;\n };\n}\n\nexport interface PerformanceMemoryInfo {\n usedJSHeapSize: number;\n totalJSHeapSize: number;\n jsHeapSizeLimit: number;\n}\n\nexport interface PerformanceWithMemory extends Performance {\n memory?: PerformanceMemoryInfo;\n measureUserAgentSpecificMemory?: () => Promise<unknown>;\n}\n\nexport interface LargestContentfulPaintEntry extends PerformanceEntry {\n renderTime?: number;\n loadTime?: number;\n}\n\n// ============================================================================\n// BEACON CONFIGURATION\n// ============================================================================\n\n/**\n * Who the current visitor is, when the host site knows.\n *\n * Deliberately just the id. The pixel's `identify` call also carries\n * `previousId` and `userTraits`, but those drive the server's profile and\n * alias-graph pipeline (tenant salt, profile-copy, write advisory locks),\n * which the beacon ingest route does not run — accepting them here would mean\n * collecting personal data the beacon path then silently discards. Both are\n * additive later: this is an optional field on an optional object.\n */\nexport interface BeaconIdentity {\n /**\n * The host site's own id for the signed-in user. Capped at 255 characters\n * to match `detections.user_id`; a longer value is rejected at ingest.\n */\n userId: string;\n}\n\n/** The beacon's automatic sends, each switchable off. See `BeaconConfig.triggers`. */\nexport interface BeaconDispatchTriggers {\n /** The `pageview` at construction and on consent restore. */\n arrival?: boolean;\n /** The follow-up send when the lazy signals chunk resolves after arrival missed it. */\n signals?: boolean;\n /** First interaction, first timing sample, and evidence growth. */\n interaction?: boolean;\n /** The first script-dispatched (untrusted) input. */\n untrusted?: boolean;\n /** An interaction after the posture token has gone stale. */\n posture?: boolean;\n /** The SDK-wired `visibilitychange` and `pagehide` critical send. */\n unload?: boolean;\n /**\n * The `pageview` for a page the visitor arrives at without a full load: a\n * back/forward-cache restore (`pageshow` with `persisted`, trigger\n * `bfcache_restore`) and a soft navigation that changes the path\n * (History API or Navigation API, trigger `soft_navigation`). Turn it off\n * when the host already calls `collect('pageview')` on its own route\n * changes, or each one sends twice.\n */\n navigation?: boolean;\n}\n\nexport interface BeaconConfig {\n /** Project ID for tracking (same as pixel data-project-id) */\n projectId: string;\n\n /**\n * Who the visitor is, when the page already knows at construction time.\n * When identity only becomes known later (a login part-way through the\n * session), call `identify()` instead.\n */\n identity?: BeaconIdentity;\n\n /**\n * Where batches are POSTed. Defaults to the hosted ingest endpoint declared\n * in `NETWORK_CONTRACT.md`.\n *\n * Set it to send somewhere else — a self-hosted deployment, a regional\n * install, or a test origin. An override means the destination is the\n * integrator's, not ours, so `NETWORK_CONTRACT.md` describes the DEFAULT and\n * says so explicitly.\n *\n * @default 'https://kya.vouched.id/api/v1/beacon'\n */\n endpoint?: string;\n\n /** Optional environment tag for data segmentation */\n environment?: 'development' | 'staging' | 'production' | string;\n\n /** Optional tags for custom data segmentation */\n tags?: Record<string, string | number | boolean>;\n\n /**\n * Not read by the SDK. Construct the beacon only when it should run, and\n * call `destroy()` to stop it.\n *\n * @deprecated\n */\n enabled?: boolean;\n\n /**\n * Verbose console logging.\n *\n * @default false\n */\n debug?: boolean;\n\n /**\n * Log verbosity.\n *\n * @default 'error'\n */\n logLevel?: 'error' | 'warn' | 'info' | 'debug';\n\n /**\n * When the browser sends Do Not Track, the beacon collects and sends nothing.\n *\n * @default true\n */\n respectDoNotTrack?: boolean;\n\n /**\n * Accepted and ignored. The beacon no longer withholds anything on\n * consent; only Do Not Track stops collection.\n *\n * @deprecated has no effect\n * @default false\n */\n requireConsent?: boolean;\n\n /**\n * Truncate the stored IP to /24 (IPv4) or /48 (IPv6) before persistence.\n *\n * @default false\n */\n anonymizeIp?: boolean;\n\n /**\n * Strip the `#fragment` from the `url`/`referrer` collector fields before\n * they leave the page. Defaults to `true`: a fragment is never sent to\n * the server by the browser in the first place for any OTHER surface\n * (it is script-visible only), so a beacon that forwards it is the one\n * place it can leak — and it is also the highest-risk part of the URL,\n * since SPA routers, magic-link auth, and OAuth implicit-flow responses\n * all put tokens there. Set to `false` only if a project genuinely\n * consumes `url`'s fragment server-side.\n *\n * @default true\n */\n stripUrlFragment?: boolean;\n\n /**\n * Query parameter names (matched case-insensitively) to redact from the\n * `url`/`referrer` collector fields before they leave the page. Each\n * matching value is replaced with the literal string `\"[redacted]\"`; the\n * parameter itself stays present so the URL's shape is unchanged. Empty\n * by default — nothing is scrubbed unless a project opts in with the\n * param names it puts tokens/PII behind (e.g. `[\"token\", \"email\"]`).\n * Ignored for a parameter when `dropQueryParams` is also `true`, since\n * there is no query string left to scrub.\n *\n * @default []\n */\n scrubQueryParams?: string[];\n\n /**\n * Drop the entire query string from the `url`/`referrer` collector\n * fields before they leave the page. Off by default. Takes priority over\n * `scrubQueryParams` when both are set — there is nothing left to scrub\n * once the whole query string is gone.\n *\n * @default false\n */\n dropQueryParams?: boolean;\n\n /**\n * Idle-gap override in milliseconds, at most six hours. Unset: one hour on\n * phones, six hours elsewhere. Every send extends it.\n */\n sessionTimeout?: number;\n\n /**\n * Name of the visitor session cookie shared by pixel, beacon, gateway, and\n * SDK rows. Query it with `?sessionId=` on the\n * [detections endpoint](/docs/api-reference#get-project-detections).\n *\n * @default '_as_beacon_session'\n */\n sessionCookieName?: string;\n\n /**\n * Resume a browser session id the page stored earlier (a receipt's\n * `browserSessionId`, see `onReceipt`) instead of reading the session\n * cookie or minting a new id. With cookies off this is the only way two\n * page loads stay one session, and a posture token verifies only against\n * the session id it was issued to. 1 to 255 characters of\n * `A-Z a-z 0-9 . _ ~ -`; anything else is ignored with a warning.\n * `updateConfig({ browserSessionId })` switches a running beacon to it.\n */\n browserSessionId?: string;\n\n /**\n * Called with every ingest receipt: the server's session id, the browser\n * session id the batch was sent under, and the posture token or the reason\n * there is none. Runs on the main thread in worker mode too, after the\n * posture cookie write. An error it throws is logged at `warn` and never\n * affects delivery.\n */\n onReceipt?: (receipt: BeaconReceipt) => void;\n\n /**\n * @deprecated The beacon no longer batches; every dispatch sends\n * immediately. Accepted and ignored so a caller upgrading from an older\n * SDK version keeps compiling and does not need to touch its config.\n */\n batchSize?: number;\n\n /**\n * @deprecated The beacon no longer polls on an interval; it dispatches on\n * evidence transitions instead (arrival, first interaction, evidence\n * doubling, untrusted input, posture staleness, hidden/pagehide). Accepted\n * and ignored so a caller upgrading from an older SDK version keeps\n * compiling and does not need to touch its config.\n */\n flushInterval?: number;\n\n /**\n * How much `keyDwellCount + pressCount + untrustedEvents` has to grow, as a\n * multiple of its value at the last send, before an interaction sends\n * again. 2 sends at 1, 2, 4, 8, 16 samples; 1.5 sends more often, 3 less.\n * A value at or below 1 falls back to the default.\n *\n * @default 2\n */\n evidenceGrowthFactor?: number;\n\n /**\n * Fraction of the posture token's lifetime after which a counted\n * interaction sends again, so the token stays fresh under a live hand.\n * 0.5 refreshes the 120 s token once an interaction lands more than 60 s\n * after the last send. A value outside (0, 1] falls back to the default.\n *\n * @default 0.5\n */\n postureRefreshFraction?: number;\n\n /**\n * Which automatic sends fire. Every trigger is on unless set to `false`.\n * Turning `unload` off leaves `trackPageUnload()` available for a host\n * that wires its own listener; turning `arrival` off leaves `collect()`.\n */\n triggers?: BeaconDispatchTriggers;\n\n /**\n * Low-frequency backstop that refreshes posture on a jittered timer,\n * independent of interaction, so a visitor who goes idle past the posture\n * TTL with no counted interaction is not one stale click on a critical\n * action away from an expired token (H0BB5, PR #5095 review). The actual\n * interval on each tick is `proactiveRefreshMinIntervalMs` plus a random\n * `[0, max - min)` jitter, so a fleet of clients loaded at the same moment\n * does not all refresh on the same wall-clock boundary. Paused while the\n * page is hidden, resumed on `visibilitychange`. Gated by\n * `triggers.posture`, the same switch that already turns off the\n * interaction-triggered staleness check — this timer is that same\n * `'posture'` trigger firing proactively, not a second mechanism. A\n * non-positive value falls back to the default.\n *\n * @default 30000\n */\n proactiveRefreshMinIntervalMs?: number;\n\n /**\n * The upper bound of the proactive-refresh jitter window; see\n * `proactiveRefreshMinIntervalMs`. A non-positive value falls back to the\n * default; a value below `proactiveRefreshMinIntervalMs` degrades to the\n * minimum on every tick rather than throwing.\n *\n * @default 60000\n */\n proactiveRefreshMaxIntervalMs?: number;\n\n /**\n * How old the last send must be, in milliseconds, before a visibility\n * resume forces an immediate posture refresh. Defaults to the same\n * threshold the interaction-triggered check already uses\n * (`postureRefreshFraction` of the posture token's lifetime), so the two\n * stay in lockstep unless a host deliberately wants the visibility check\n * to be stricter or looser. A non-positive value falls back to that\n * default.\n */\n proactiveRefreshFreshnessMs?: number;\n\n /**\n * On `visibilitychange` back to visible, force an immediate posture\n * refresh when it is stale (see `proactiveRefreshFreshnessMs`); a fresh\n * tab regaining focus does not get an unnecessary send either way. Set to\n * `false` to leave visibility resume to the plain interval alone.\n *\n * @default true\n */\n proactiveRefreshOnVisibilityResume?: boolean;\n\n /**\n * Refresh posture (and drain anything the offline queue is still holding)\n * when the browser fires `online`. Set to `false` to leave reconnection\n * recovery to the offline queue's own `online` listener alone.\n *\n * @default true\n */\n proactiveRefreshOnOnline?: boolean;\n\n /**\n * A fixed seed for the proactive-refresh jitter roll, for deterministic\n * tests. Omit in production for real `Math.random()` jitter.\n */\n proactiveRefreshJitterSeed?: number;\n\n /**\n * Per-collector deadline in milliseconds. A collector still running past\n * this deadline is dropped from the current collection round rather than\n * awaited further — see `collectWithDeadline` in checkpoint-beacon.\n * Default and rationale documented in checkpoint-beacon's\n * `src/budget/thresholds.ts`.\n *\n * @default 1600\n */\n collectorDeadlineMs?: number;\n\n /**\n * Maximum number of queued events.\n *\n * @default 100\n */\n maxQueueSize?: number;\n\n /**\n * Retry count for failed sends.\n *\n * @default 3\n */\n retryAttempts?: number;\n\n /**\n * Base retry delay in milliseconds.\n *\n * @default 2000\n */\n retryDelay?: number;\n\n /**\n * Delays in milliseconds between posture-recovery attempts after a\n * durably-queued ingest response that carried no posture verdict. The\n * array's length is the attempt ceiling. Defaults to the shipped ladder;\n * override only in tests and in a self-hosted deployment with a\n * different outage profile.\n */\n postureRetryScheduleMs?: number[];\n\n /**\n * Prefer a Web Worker for event processing, batching, and transport.\n * Page-dependent collection remains on the main thread. Unsupported\n * browsers fall back to the main thread; SSR never starts a worker.\n * Set false to disable the processing worker.\n *\n * @default true\n */\n useWorker?: boolean;\n\n /**\n * Alias for `useWorker`, accepted for callers using the older option\n * name. When both are set, `useWorker` wins — see `resolveUseWorker`.\n */\n enableWebWorker?: boolean;\n\n /**\n * URL of the worker script (`beacon.worker.js`, exported as\n * `@kya-os/checkpoint-beacon/worker`). Classic workers must be same-origin.\n * When unset, the beacon derives `beacon.worker.js` next to the `<script>`\n * tag that loaded `beacon.min.js`, else `/beacon.worker.js` at the site root.\n */\n workerUrl?: string;\n\n /**\n * Worker lifecycle tuning: `initTimeoutMs` (3000), `messageTimeout` (30000),\n * `heartbeatInterval` (5000), `maxRetries` (3), `retryDelay` (1000),\n * `compressionThreshold` (5120), `allowFallback` (true).\n */\n workerConfig?: WorkerConfig;\n\n lazySignalsUrl?: string;\n}\n\n// ============================================================================\n// BEACON EVENTS\n// ============================================================================\n\nexport interface BeaconEvent {\n /** Event type identifier */\n type: BeaconEventType;\n\n /** Event data payload */\n data: BeaconCollectorData;\n\n /** Event metadata */\n metadata: BeaconMetadata;\n}\n\nexport interface BeaconMetadata {\n /** Session ID */\n sessionId: string;\n\n /** Event timestamp */\n timestamp: number;\n\n /** Optional event name */\n eventName?: string;\n\n /** Present only once the host site has told us who the visitor is. */\n identity?: BeaconIdentity;\n\n /** Allow additional metadata */\n [key: string]: unknown;\n}\n\n// ============================================================================\n// BEACON API\n// ============================================================================\n\nexport interface IAgentShieldBeacon {\n /**\n * Collect a generic event\n */\n collect(eventType: string, data?: BeaconPayload): Promise<void>;\n\n /**\n * Track a custom event\n */\n trackEvent(eventName: string, eventData?: BeaconPayload): Promise<void>;\n\n /**\n * Track a pageview\n */\n trackPageview(pageData?: BeaconPayload): Promise<void>;\n\n /**\n * Track page unload\n */\n trackPageUnload(): Promise<void>;\n\n /**\n * Update configuration\n */\n updateConfig(updates: Partial<BeaconConfig>): void;\n\n /**\n * Destroy the beacon and clean up\n */\n destroy(): Promise<void>;\n}\n\n// ============================================================================\n// RESPONSE TYPES\n// ============================================================================\n\nexport interface BeaconResponse {\n /** Response status */\n status: 'success' | 'error';\n\n /** Optional message */\n message?: string;\n\n /** Optional error details */\n error?: {\n code: string;\n message: string;\n };\n}\n\n// ============================================================================\n// BROWSER CONTEXT\n// ============================================================================\n\nexport interface BrowserContext {\n /** Browser name and version */\n browser: {\n name: string;\n version: string;\n engine: string;\n };\n\n /** Operating system */\n os: {\n name: string;\n version: string;\n };\n\n /** Device information */\n device: {\n type: 'desktop' | 'mobile' | 'tablet' | 'tv' | 'unknown';\n vendor?: string;\n model?: string;\n };\n\n /** Screen information */\n screen: {\n width: number;\n height: number;\n pixelRatio: number;\n colorDepth: number;\n };\n\n /** Connection information */\n connection?: {\n type: 'bluetooth' | 'cellular' | 'ethernet' | 'none' | 'wifi' | 'wimax' | 'other' | 'unknown';\n effectiveType?: '2g' | '3g' | '4g' | '5g';\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n };\n}\n\n// ============================================================================\n// PERFORMANCE METRICS\n// ============================================================================\n\nexport interface PerformanceMetrics {\n /** Page load time in milliseconds */\n pageLoadTime?: number;\n\n /** DOM content loaded time */\n domContentLoadedTime?: number;\n\n /** Time to interactive */\n timeToInteractive?: number;\n\n /** First paint time */\n firstPaintTime?: number;\n\n /** First contentful paint time */\n firstContentfulPaintTime?: number;\n\n /** Largest contentful paint time */\n largestContentfulPaintTime?: number;\n\n /** DNS lookup time */\n dnsLookupTime?: number;\n\n /** TCP connection time */\n tcpConnectionTime?: number;\n\n /** Server response time */\n serverResponseTime?: number;\n\n /** Resource timing */\n resources?: {\n scripts: number;\n stylesheets: number;\n images: number;\n fonts: number;\n total: number;\n };\n}\n\n// ============================================================================\n// SESSION TYPES\n// ============================================================================\n\nexport interface SessionData {\n /** Unique session ID */\n id: string;\n\n /** Session start timestamp */\n startTime: number;\n\n /** Last activity timestamp */\n lastActivity: number;\n\n /** Page view count in session */\n pageViews: number;\n\n /** Event count in session */\n eventCount: number;\n\n /** Session duration in milliseconds */\n duration: number;\n\n /** Is this a new session */\n isNew: boolean;\n}\n\n// ============================================================================\n// TRANSPORT TYPES\n// ============================================================================\n\nexport interface TransportConfig {\n maxRetries: number;\n retryDelayBase: number;\n offlineQueueSize: number;\n useCompression: boolean;\n compressionThreshold: number;\n /** Build item 6: carried onto every outgoing `BeaconBatch` — see `BeaconConfig.anonymizeIp`. */\n anonymizeIp?: boolean;\n}\n\nexport interface TransportOptions {\n immediate?: boolean;\n priority?: 'low' | 'normal' | 'high' | 'critical';\n retry?: boolean;\n timeout?: number;\n publicJwk?: EcPublicJwk;\n deviceId?: string;\n handoffToken?: string;\n}\n\nexport interface TransportResponse {\n success: boolean;\n timestamp: number;\n batchId?: string;\n error?: string;\n}\n\nexport type TransportState = 'idle' | 'sending' | 'offline' | 'paused' | 'error';\n\nexport interface TransportMetrics {\n eventsSent: number;\n eventsFailed: number;\n eventsQueued: number;\n batchesSent: number;\n batchesFailed: number;\n bytesTransferred: number;\n compressionRatio?: number;\n averageLatency?: number;\n lastSuccessTimestamp?: number;\n lastErrorTimestamp?: number;\n}\n\nexport type ConnectionType =\n | 'bluetooth'\n | 'cellular'\n | 'ethernet'\n | 'none'\n | 'wifi'\n | 'wimax'\n | 'other'\n | 'unknown';\n\nexport interface NetworkInfo {\n type?: string;\n effectiveType?: string;\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n}\n\n// ============================================================================\n// WORKER TYPES\n// ============================================================================\n\nexport type MessagePriority = 'low' | 'normal' | 'high' | 'critical';\nexport type WorkerErrorType =\n | 'initialization'\n | 'runtime'\n | 'communication'\n | 'timeout'\n | 'memory'\n | 'network'\n | 'permission'\n | 'validation'\n | 'processing'\n | 'unknown';\nexport type WorkerAction =\n | 'process'\n | 'init'\n | 'terminate'\n | 'pause'\n | 'resume'\n | 'status'\n | 'health';\nexport type WorkerMessageType = 'request' | 'response' | 'error' | 'heartbeat' | 'status';\n\nexport interface WorkerMessage {\n id: string;\n type: 'request' | 'response' | 'error' | 'heartbeat' | 'status';\n action?: string;\n payload?: WorkerPayload;\n timestamp: number;\n compressed?: boolean;\n priority?: MessagePriority;\n correlationId?: string;\n}\n\nexport type WorkerState =\n | 'idle'\n | 'initializing'\n | 'ready'\n | 'processing'\n | 'busy'\n | 'error'\n | 'terminating'\n | 'terminated';\n\nexport type WorkerHealthStatus = 'healthy' | 'degraded' | 'unhealthy' | 'unknown';\n\nexport interface WorkerMetrics {\n tasksProcessed: number;\n tasksFailed: number;\n averageProcessingTime?: number;\n memoryUsage?: number;\n cpuUsage?: number;\n healthStatus: WorkerHealthStatus;\n lastHealthCheck: number;\n restartCount: number;\n errorRate?: number;\n errorCount: number;\n messageQueueSize: number;\n startTime: number;\n uptime: number;\n averageTaskTime?: number;\n lastTaskTime?: number;\n}\n\nexport interface WorkerError {\n type: WorkerErrorType;\n code?: string;\n message: string;\n stack?: string;\n timestamp: number;\n recoverable: boolean;\n retryAfter?: number;\n context?: Record<string, unknown>;\n}\n\nexport interface WorkerCapabilities {\n workerAPI: boolean;\n sharedArrayBuffer: boolean;\n transferableObjects: boolean;\n offscreenCanvas: boolean;\n webAssembly: boolean;\n atomics: boolean;\n bigInt: boolean;\n csp: {\n workerSrc: boolean;\n scriptSrc: boolean;\n blobUrls: boolean;\n inlineWorkers: boolean;\n };\n performance: {\n memory: boolean;\n measureUserAgentSpecificMemory: boolean;\n };\n}\n\nexport interface WorkerTask {\n id: string;\n type: string;\n data: WorkerPayload;\n priority: 'low' | 'normal' | 'high' | 'critical';\n createdAt: number;\n startedAt?: number;\n completedAt?: number;\n error?: WorkerError;\n maxRetries?: number;\n retries?: number;\n timeout?: number;\n}\n\nexport interface FallbackOptions {\n useRequestIdleCallback: boolean;\n idleTimeout: number;\n chunkSize: number;\n throttleMs: number;\n maxExecutionTime: number;\n}\n\nexport interface ResourceUsage {\n memory: {\n used: number;\n limit: number;\n percentage: number;\n };\n cpu: {\n usage: number;\n limit: number;\n };\n tasks: {\n pending: number;\n active: number;\n completed: number;\n failed: number;\n };\n activeWorkers: number;\n}\n\nexport interface WorkerPoolConfig {\n maxWorkers: number;\n minWorkers: number;\n workerIdleTimeout: number;\n taskQueueSize: number;\n resourceLimits: Record<string, number>;\n autoScale?: boolean;\n scaleUpThreshold?: number;\n scaleDownThreshold?: number;\n}\n\nexport type BeaconWorkerMessageType =\n | 'init'\n | 'collect'\n | 'flush'\n | 'config'\n | 'status'\n | 'error'\n | 'response'\n // Unsolicited worker -> main relay of a 202 ingest body (posture cookie\n // delivery needs `document`, which the worker lacks).\n | 'posture';\nexport type ProtocolVersion = '1.0' | '1.1' | '2.0';\n\nexport interface BeaconWorkerMessage {\n type: BeaconWorkerMessageType;\n data?: WorkerPayload;\n payload?: WorkerPayload;\n messageId: string;\n timestamp: number;\n id: string;\n}\n\nexport interface WorkerConfig {\n enabled?: boolean;\n url?: string;\n heartbeatInterval?: number;\n maxUnhealthyCount?: number;\n maxRetries?: number;\n retryDelay?: number;\n restartDelay?: number;\n messageTimeout?: number;\n compressionThreshold?: number;\n allowFallback?: boolean;\n crossOriginIsolated?: boolean;\n maxRestartAttempts?: number;\n terminationTimeout?: number;\n taskTimeout?: number;\n fallbackDelay?: number;\n enableFallback?: boolean;\n /**\n * Hard ceiling on how long worker startup (script load + init handshake)\n * gets before the caller gives up and falls back to the main-thread\n * transport. Deliberately separate from `taskTimeout`/`messageTimeout`\n * (which govern steady-state message round trips once the worker is\n * already up): a slow or hung worker script would otherwise hold up\n * every event for the full 30s message timeout before anything left the\n * page. A few seconds is enough for a healthy worker to load and answer\n * its init message; anything slower isn't worth waiting on.\n */\n initTimeoutMs?: number;\n}\n\n// ============================================================================\n// CIRCUIT BREAKER & RETRY\n// ============================================================================\n\nexport interface CircuitBreakerConfig {\n threshold: number;\n timeout: number;\n resetTimeout: number;\n}\n\nexport type CircuitBreakerState = 'closed' | 'open' | 'half-open';\n\nexport interface RetryStrategy {\n maxAttempts: number;\n baseDelay: number;\n maxDelay: number;\n factor: number;\n jitter: boolean;\n}\n\n// ============================================================================\n// OFFLINE QUEUE\n// ============================================================================\n\nexport interface OfflineQueueEntry {\n id: string;\n events: BeaconEvent[];\n timestamp: number;\n expiresAt: number;\n retryCount: number;\n size: number;\n}\n\n// ============================================================================\n// BEACON BATCH\n// ============================================================================\n\n/** The minimal EC-P256 public JWK shape the beacon can construct without\n * a JOSE library dependency (see P37's findings on bundle-size discipline).\n * Structurally compatible with `jose`'s wider `JWK` type on the server side. */\nexport interface EcPublicJwk {\n kty: 'EC';\n crv: 'P-256';\n x: string;\n y: string;\n}\n\n/** What `BeaconConfig.onReceipt` receives for each 202 ingest response. */\nexport interface BeaconReceipt {\n /**\n * The server's session id for this visit, the key\n * `GET /api/v1/projects/{id}/sessions/{sessionId}` reads. On a receipt from\n * the queue-only edge it is present once the origin has answered for the\n * session, and absent before (`postureStatus: 'pending'`).\n */\n sessionId?: string;\n /**\n * The beacon's own session id the batch was sent under: what a posture\n * token is bound to, and what `BeaconConfig.browserSessionId` resumes.\n */\n browserSessionId: string;\n /** The signed posture token, when ingest issued one. `expiresAt` is Unix seconds. */\n posture?: { token: string; expiresAt: number };\n /** Why `posture` is absent: `'pending'` while a queued batch awaits replay, otherwise the withheld reason. */\n postureStatus?: string;\n}\n\nexport interface BeaconBatch {\n projectId: string;\n events: BeaconEvent[];\n sessionId: string;\n handoffToken?: string;\n deviceId?: string;\n batchId: string;\n timestamp: number;\n /** Build item 6: mirrors `BeaconConfig.anonymizeIp` (default `false`) — see the beacon route's own doc comment. */\n anonymizeIp?: boolean;\n /** Nonce-bound ingest (build item 5): the value from the prior 202 response's `nonce`. */\n nonce?: string;\n /** Nonce-bound ingest (build item 5): declares this client echoes nonces — see checkpoint-beacon's `BeaconBatch`. */\n nonceEcho?: boolean;\n /** Holder-of-key posture binding (P37): the beacon's own DPoP public key,\n * sent once per browser session (first batch only) so the issuer can bind\n * every subsequent posture mint to it via `cnf.jkt`. */\n publicJwk?: EcPublicJwk;\n}\n\nexport interface BeaconCollectorData {\n // Browser collector data\n userAgent?: string;\n language?: string;\n platform?: string;\n screenResolution?: string;\n viewport?: string;\n cookiesEnabled?: boolean;\n doNotTrack?: boolean;\n timezone?: string;\n referrer?: string;\n url?: string;\n title?: string;\n vendor?: string;\n\n // Performance collector data\n pageLoadTime?: number;\n domContentLoadedTime?: number;\n firstPaintTime?: number;\n firstContentfulPaintTime?: number;\n connectionType?: string;\n\n // Session data\n sessionId?: string;\n timestamp?: number;\n\n // Allow additional properties\n [key: string]: unknown;\n}\n\nexport type BeaconEventType =\n | 'pageview'\n | 'pageunload'\n | 'heartbeat'\n | 'evidence'\n | 'custom'\n | 'error'\n | 'performance';\n\n// ============================================================================\n// PARSER FUNCTIONS\n// ============================================================================\n\nexport function parseRetryStrategy(input: unknown): RetryStrategy {\n const strategy = toRecord(input);\n return {\n maxAttempts: numberOr(strategy.maxAttempts, 3),\n baseDelay: numberOr(strategy.baseDelay, 1000),\n maxDelay: numberOr(strategy.maxDelay, 30000),\n factor: numberOr(strategy.factor, 2),\n jitter: strategy.jitter !== false,\n };\n}\n\nexport function parseCircuitBreakerConfig(input: unknown): CircuitBreakerConfig {\n const config = toRecord(input);\n return {\n threshold: numberOr(config.threshold, 5),\n timeout: numberOr(config.timeout, 60000),\n resetTimeout: numberOr(config.resetTimeout, 30000),\n };\n}\n\nexport function parseOfflineQueueEntry(input: unknown): OfflineQueueEntry {\n if (!isRecord(input)) {\n throw new Error('Invalid offline queue entry');\n }\n\n const entry = input;\n return {\n id: stringOr(\n entry.id,\n `${Date.now()}_${Array.from(crypto.getRandomValues(new Uint8Array(6)), (byte) => byte.toString(16).padStart(2, '0')).join('')}`\n )!,\n events: Array.isArray(entry.events) ? (entry.events as BeaconEvent[]) : [],\n timestamp: numberOr(entry.timestamp, Date.now()),\n expiresAt: numberOr(entry.expiresAt, Date.now() + 86400000), // 24 hours\n retryCount: numberOr(entry.retryCount, 0),\n size: numberOr(entry.size, 0),\n };\n}\n\nfunction randomId(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nexport function parseBeaconWorkerMessage(input: unknown): BeaconWorkerMessage {\n if (!isRecord(input)) {\n throw new Error('Invalid beacon worker message');\n }\n\n const msg = input;\n const messageId = stringOr(msg.messageId) ?? stringOr(msg.id) ?? randomId();\n return {\n type: isBeaconWorkerMessageType(msg.type) ? msg.type : 'init',\n data: msg.data,\n payload: msg.payload,\n messageId,\n timestamp: numberOr(msg.timestamp, Date.now()),\n id: stringOr(msg.id, messageId)!,\n };\n}\n\nfunction isMessagePriority(value: unknown): value is MessagePriority {\n return value === 'low' || value === 'normal' || value === 'high' || value === 'critical';\n}\n\nfunction isWorkerMessageType(value: unknown): value is WorkerMessageType {\n return (\n value === 'request' ||\n value === 'response' ||\n value === 'error' ||\n value === 'heartbeat' ||\n value === 'status'\n );\n}\n\nfunction isWorkerErrorType(value: unknown): value is WorkerErrorType {\n return (\n value === 'initialization' ||\n value === 'runtime' ||\n value === 'communication' ||\n value === 'timeout' ||\n value === 'memory' ||\n value === 'network' ||\n value === 'permission' ||\n value === 'validation' ||\n value === 'processing' ||\n value === 'unknown'\n );\n}\n\nexport function parseWorkerMessage(input: unknown): WorkerMessage {\n const msg = (input && typeof input === 'object' ? input : null) as Partial<WorkerMessage> | null;\n if (!msg) {\n throw new Error('Invalid worker message');\n }\n\n return {\n id: msg.id || randomId(),\n type: isWorkerMessageType(msg.type) ? msg.type : 'request',\n action: msg.action,\n payload: msg.payload,\n timestamp: msg.timestamp || Date.now(),\n compressed: msg.compressed,\n priority: isMessagePriority(msg.priority) ? msg.priority : 'normal',\n correlationId: msg.correlationId,\n };\n}\n\nexport function parseWorkerError(input: unknown): WorkerError {\n const error = (input && typeof input === 'object' ? input : {}) as Partial<WorkerError>;\n return {\n type: isWorkerErrorType(error.type) ? error.type : 'unknown',\n code: typeof error.code === 'string' ? error.code : undefined,\n message: typeof error.message === 'string' ? error.message : 'Worker error',\n stack: typeof error.stack === 'string' ? error.stack : undefined,\n timestamp: typeof error.timestamp === 'number' ? error.timestamp : Date.now(),\n recoverable: error.recoverable !== false,\n retryAfter: typeof error.retryAfter === 'number' ? error.retryAfter : undefined,\n context: error.context,\n };\n}\n\nexport function parseWorkerPoolConfig(input: unknown): WorkerPoolConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Partial<WorkerPoolConfig>;\n return {\n maxWorkers: config.maxWorkers ?? 4,\n minWorkers: config.minWorkers ?? 1,\n workerIdleTimeout: config.workerIdleTimeout ?? 30000,\n taskQueueSize: config.taskQueueSize ?? 100,\n resourceLimits: config.resourceLimits ?? {},\n autoScale: config.autoScale ?? true,\n scaleUpThreshold: config.scaleUpThreshold ?? 75,\n scaleDownThreshold: config.scaleDownThreshold ?? 25,\n };\n}\n\nexport function parseResourceUsage(input: unknown): ResourceUsage {\n const usage = (input && typeof input === 'object' ? input : {}) as Partial<ResourceUsage>;\n return {\n memory: usage.memory ?? { used: 0, limit: 0, percentage: 0 },\n cpu: usage.cpu ?? { usage: 0, limit: 100 },\n tasks: usage.tasks ?? { pending: 0, active: 0, completed: 0, failed: 0 },\n activeWorkers: usage.activeWorkers ?? 0,\n };\n}\n\nexport const ResourceUsageSchema = {\n parse: parseResourceUsage,\n};\n\nexport const WorkerPoolConfigSchema = {\n parse: parseWorkerPoolConfig,\n};\n\nexport function parseWorkerCapabilities(input: unknown): WorkerCapabilities {\n const cap = toRecord(input);\n const csp = toRecord(cap.csp);\n const performance = toRecord(cap.performance);\n\n return {\n workerAPI: cap.workerAPI !== false,\n sharedArrayBuffer: cap.sharedArrayBuffer === true,\n transferableObjects: cap.transferableObjects === true,\n offscreenCanvas: cap.offscreenCanvas === true,\n webAssembly: cap.webAssembly === true,\n atomics: cap.atomics === true,\n bigInt: cap.bigInt === true,\n csp: {\n workerSrc: csp.workerSrc === true,\n scriptSrc: csp.scriptSrc === true,\n blobUrls: csp.blobUrls === true,\n inlineWorkers: csp.inlineWorkers === true,\n },\n performance: {\n memory: performance.memory === true,\n measureUserAgentSpecificMemory: performance.measureUserAgentSpecificMemory === true,\n },\n };\n}\n\n/**\n * @param onWarn Called once per rejected config value (a supplied value that\n * failed validation and fell back to its default), for a caller that wants\n * to surface it — `BeaconConfigManager.validateAndMergeConfig` wires this to\n * `log('warn', ...)`. Never called for an omitted field; only for one the\n * caller actually set to something invalid.\n */\nexport function parseBeaconConfig(\n input: unknown,\n onWarn?: (message: string) => void\n): BeaconConfig {\n const config = toRecord(input);\n\n if (typeof config.projectId !== 'string' || config.projectId.length === 0) {\n throw new Error('Project ID is required');\n }\n\n return {\n projectId: config.projectId,\n environment: stringOr(config.environment),\n tags: isBeaconTags(config.tags) ? config.tags : undefined,\n identity: isBeaconIdentity(config.identity) ? config.identity : undefined,\n // `parseBeaconConfig` is an allowlist: a key it does not name is dropped\n // silently, which is how `identity` first shipped inert.\n endpoint: stringOr(config.endpoint),\n enabled: config.enabled !== false,\n debug: config.debug === true,\n logLevel: isLogLevel(config.logLevel) ? config.logLevel : 'error',\n respectDoNotTrack: config.respectDoNotTrack !== false,\n requireConsent: config.requireConsent === true,\n anonymizeIp: config.anonymizeIp === true,\n stripUrlFragment: config.stripUrlFragment !== false,\n scrubQueryParams: isStringArray(config.scrubQueryParams) ? config.scrubQueryParams : undefined,\n dropQueryParams: config.dropQueryParams === true,\n sessionTimeout: numberOr(config.sessionTimeout, undefined),\n sessionCookieName: stringOr(config.sessionCookieName, '_as_beacon_session'),\n browserSessionId: resumableSessionId(config.browserSessionId, (received) =>\n onWarn?.(\n `browserSessionId must match ${RESUMABLE_SESSION_ID} (received ${JSON.stringify(received)}); ignoring it`\n )\n ),\n onReceipt: receiptCallback(config.onReceipt, (received) =>\n onWarn?.(`onReceipt must be a function (received ${typeof received}); ignoring it`)\n ),\n // Deprecated no-ops (see BeaconConfig.batchSize/flushInterval): passed\n // through when a caller sets them so a stale value round-trips through\n // `get()`, never defaulted, since nothing reads them anymore.\n batchSize: typeof config.batchSize === 'number' ? config.batchSize : undefined,\n flushInterval: typeof config.flushInterval === 'number' ? config.flushInterval : undefined,\n collectorDeadlineMs: numberOr(config.collectorDeadlineMs, 1600),\n evidenceGrowthFactor: boundedNumberOr(\n config.evidenceGrowthFactor,\n 2,\n (n) => n > 1,\n (received) =>\n onWarn?.(\n `evidenceGrowthFactor must be a number greater than 1 (received ${JSON.stringify(received)}); using default 2`\n )\n ),\n postureRefreshFraction: boundedNumberOr(\n config.postureRefreshFraction,\n 0.5,\n (n) => n > 0 && n <= 1,\n (received) =>\n onWarn?.(\n `postureRefreshFraction must be a number in (0, 1] (received ${JSON.stringify(received)}); using default 0.5`\n )\n ),\n triggers: pickTriggers(config.triggers, (name, received) =>\n onWarn?.(\n `triggers.${name} must be a boolean (received ${JSON.stringify(received)}); ignoring it and keeping its default`\n )\n ),\n maxQueueSize: numberOr(config.maxQueueSize, 100),\n retryAttempts: numberOr(config.retryAttempts, 3),\n retryDelay: numberOr(config.retryDelay, 2000),\n postureRetryScheduleMs: isPositiveNumberArray(config.postureRetryScheduleMs)\n ? config.postureRetryScheduleMs\n : undefined,\n useWorker: resolveUseWorker(config),\n workerUrl: stringOr(config.workerUrl),\n workerConfig: isRecord(config.workerConfig) ? (config.workerConfig as WorkerConfig) : undefined,\n lazySignalsUrl: stringOr(config.lazySignalsUrl),\n proactiveRefreshMinIntervalMs: boundedNumberOr(\n config.proactiveRefreshMinIntervalMs,\n 30_000,\n (n) => n > 0,\n (received) =>\n onWarn?.(\n `proactiveRefreshMinIntervalMs must be a positive number (received ${JSON.stringify(received)}); using default 30000`\n )\n ),\n proactiveRefreshMaxIntervalMs: boundedNumberOr(\n config.proactiveRefreshMaxIntervalMs,\n 60_000,\n (n) => n > 0,\n (received) =>\n onWarn?.(\n `proactiveRefreshMaxIntervalMs must be a positive number (received ${JSON.stringify(received)}); using default 60000`\n )\n ),\n proactiveRefreshFreshnessMs: optionalPositiveNumber(\n config.proactiveRefreshFreshnessMs,\n (received) =>\n onWarn?.(\n `proactiveRefreshFreshnessMs must be a positive number (received ${JSON.stringify(received)}); ignoring it and inheriting postureRefreshFraction's threshold`\n )\n ),\n proactiveRefreshOnVisibilityResume: booleanOr(\n config.proactiveRefreshOnVisibilityResume,\n true,\n (received) =>\n onWarn?.(\n `proactiveRefreshOnVisibilityResume must be a boolean (received ${JSON.stringify(received)}); using default true`\n )\n ),\n proactiveRefreshOnOnline: booleanOr(config.proactiveRefreshOnOnline, true, (received) =>\n onWarn?.(\n `proactiveRefreshOnOnline must be a boolean (received ${JSON.stringify(received)}); using default true`\n )\n ),\n proactiveRefreshJitterSeed: optionalFiniteNumber(\n config.proactiveRefreshJitterSeed,\n (received) =>\n onWarn?.(\n `proactiveRefreshJitterSeed must be a finite number (received ${JSON.stringify(received)}); ignoring it, jitter will use Math.random()`\n )\n ),\n };\n}\n\n// ============================================================================\n// EXPORT MAIN CLASS TYPE\n// ============================================================================\n\nexport declare class AgentShieldBeacon implements IAgentShieldBeacon {\n constructor(config: BeaconConfig);\n collect(eventType: string, data?: BeaconPayload): Promise<void>;\n trackEvent(eventName: string, eventData?: BeaconPayload): Promise<void>;\n trackPageview(pageData?: BeaconPayload): Promise<void>;\n trackPageUnload(): Promise<void>;\n updateConfig(updates: Partial<BeaconConfig>): void;\n destroy(): Promise<void>;\n}\n\n/**\n * The most events one beacon POST may carry. The ingest route's\n * `BeaconBatchSchema` refuses a larger batch whole (a 400, not a retry), so\n * the SDK's offline drain never dequeues more than this per request.\n */\nexport const BEACON_MAX_EVENTS_PER_BATCH = 100;\n\nexport const SESSION_IDLE_GAP_MAX_MS = 21_600_000;\nexport const BEACON_MAX_BATCH_ID_LENGTH = 255;\n\nexport const BEACON_ORIGIN_CONTRACT_VERSION = 1;\n\nexport const BEACON_ORIGIN_CAPABILITIES = [\n 'batch-replay-v1',\n 'receipt-status-v1',\n 'receipt-posture-v1',\n] as const;\n\n/**\n * Lifetime of the signed browser posture token, in seconds. Defined here and\n * re-exported by `browser-posture.ts` (which imports `jose`) so the\n * size-budgeted beacon bundle can read it without pulling in a JWT library.\n */\nexport const POSTURE_TTL_SECONDS = 120;\n\nexport interface CachedPosture {\n token: string;\n expiresAt: number;\n}\n\nexport interface PostureAnswer {\n posture?: CachedPosture;\n postureStatus?: string;\n sessionId?: string;\n answeredAtMs?: number;\n}\n\nexport function parsePostureAnswer(value: unknown): PostureAnswer {\n if (!isRecord(value)) return {};\n const answer: PostureAnswer = {};\n if (\n isRecord(value.posture) &&\n typeof value.posture.token === 'string' &&\n value.posture.token.length > 0 &&\n typeof value.posture.expiresAt === 'number' &&\n Number.isFinite(value.posture.expiresAt)\n ) {\n answer.posture = { token: value.posture.token, expiresAt: value.posture.expiresAt };\n } else if (typeof value.postureStatus === 'string' && value.postureStatus.length <= 64) {\n answer.postureStatus = value.postureStatus;\n }\n if (typeof value.sessionId === 'string' && value.sessionId.length <= 255) {\n answer.sessionId = value.sessionId;\n }\n if (typeof value.answeredAtMs === 'number' && Number.isFinite(value.answeredAtMs)) {\n answer.answeredAtMs = value.answered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