@utk09/ui-observability 0.9.4 → 0.9.5

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 (208) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +122 -94
  3. package/dist/batch-BQFtb3i5.cjs +2 -0
  4. package/dist/batch-BQFtb3i5.cjs.map +1 -0
  5. package/dist/{batch-D-4xl7op.js → batch-BUJh-1jZ.js} +7 -5
  6. package/dist/batch-BUJh-1jZ.js.map +1 -0
  7. package/dist/bus/bus.d.ts +76 -2
  8. package/dist/bus/links.d.ts +9 -2
  9. package/dist/bus/validation.d.ts +7 -0
  10. package/dist/bus-BW6N-pY8.cjs +2 -0
  11. package/dist/bus-BW6N-pY8.cjs.map +1 -0
  12. package/dist/bus-DeOPHWaD.js +647 -0
  13. package/dist/bus-DeOPHWaD.js.map +1 -0
  14. package/dist/capture/storm.d.ts +2 -1
  15. package/dist/capture/types.d.ts +2 -0
  16. package/dist/{console-Boqa7new.cjs → console-Ce6heqZZ.cjs} +2 -2
  17. package/dist/console-Ce6heqZZ.cjs.map +1 -0
  18. package/dist/{console-BT7mcgU6.js → console-DbAZYJuy.js} +4 -4
  19. package/dist/console-DbAZYJuy.js.map +1 -0
  20. package/dist/constants-CN7GE1Lt.js +246 -0
  21. package/dist/constants-CN7GE1Lt.js.map +1 -0
  22. package/dist/constants-CW-MlHdY.cjs +2 -0
  23. package/dist/constants-CW-MlHdY.cjs.map +1 -0
  24. package/dist/constants.d.ts +29 -9
  25. package/dist/context-storage-BjzeBSxH.cjs +2 -0
  26. package/dist/context-storage-BjzeBSxH.cjs.map +1 -0
  27. package/dist/context-storage-DxZf4Gfh.js +52 -0
  28. package/dist/context-storage-DxZf4Gfh.js.map +1 -0
  29. package/dist/core/breadcrumbs.d.ts +7 -2
  30. package/dist/core/context.d.ts +2 -0
  31. package/dist/core/diagnostics.d.ts +11 -3
  32. package/dist/core/meter.d.ts +6 -1
  33. package/dist/core/pipeline.d.ts +29 -2
  34. package/dist/core/record.d.ts +2 -1
  35. package/dist/core/runtime.d.ts +91 -3
  36. package/dist/core/sampling.d.ts +3 -1
  37. package/dist/core/sender.d.ts +35 -1
  38. package/dist/deadline-5_PecIl5.js +26 -0
  39. package/dist/deadline-5_PecIl5.js.map +1 -0
  40. package/dist/deadline-XSnm95pg.cjs +2 -0
  41. package/dist/deadline-XSnm95pg.cjs.map +1 -0
  42. package/dist/emergency-queue-BYUyDHGD.js +69 -0
  43. package/dist/emergency-queue-BYUyDHGD.js.map +1 -0
  44. package/dist/emergency-queue-Cs1hrjsC.cjs +2 -0
  45. package/dist/emergency-queue-Cs1hrjsC.cjs.map +1 -0
  46. package/dist/{errors-BDI96zKc.js → errors-BhC7HTSt.js} +8 -9
  47. package/dist/errors-BhC7HTSt.js.map +1 -0
  48. package/dist/errors-CgY633cG.cjs +3 -0
  49. package/dist/errors-CgY633cG.cjs.map +1 -0
  50. package/dist/factory-C5TujXlU.js +280 -0
  51. package/dist/factory-C5TujXlU.js.map +1 -0
  52. package/dist/factory-CNj4DH3n.cjs +2 -0
  53. package/dist/factory-CNj4DH3n.cjs.map +1 -0
  54. package/dist/fixed-window-CtaFHanJ.js +12 -0
  55. package/dist/fixed-window-CtaFHanJ.js.map +1 -0
  56. package/dist/fixed-window-CvESpFYV.cjs +2 -0
  57. package/dist/fixed-window-CvESpFYV.cjs.map +1 -0
  58. package/dist/identity-8vKkyAWm.js +103 -0
  59. package/dist/identity-8vKkyAWm.js.map +1 -0
  60. package/dist/identity-Da9TkuKd.cjs +2 -0
  61. package/dist/identity-Da9TkuKd.cjs.map +1 -0
  62. package/dist/index.cjs +1 -1
  63. package/dist/index.cjs.map +1 -1
  64. package/dist/index.d.ts +45 -7
  65. package/dist/index.js +908 -529
  66. package/dist/index.js.map +1 -1
  67. package/dist/indexeddb-storage-BTfIFRHF.cjs +2 -0
  68. package/dist/indexeddb-storage-BTfIFRHF.cjs.map +1 -0
  69. package/dist/{indexeddb-storage-HgkQUTyS.js → indexeddb-storage-CCA1LvtO.js} +33 -18
  70. package/dist/indexeddb-storage-CCA1LvtO.js.map +1 -0
  71. package/dist/{interactions-Ck01cEij.js → interactions-BUDLxbv1.js} +16 -12
  72. package/dist/interactions-BUDLxbv1.js.map +1 -0
  73. package/dist/interactions-NHbLKrqe.cjs +2 -0
  74. package/dist/interactions-NHbLKrqe.cjs.map +1 -0
  75. package/dist/{journey-DRK0A8u_.js → journey-BUJ4WJxP.js} +12 -12
  76. package/dist/{journey-DRK0A8u_.js.map → journey-BUJ4WJxP.js.map} +1 -1
  77. package/dist/{journey-Co9OlzrW.cjs → journey-B_tTnvac.cjs} +2 -2
  78. package/dist/{journey-Co9OlzrW.cjs.map → journey-B_tTnvac.cjs.map} +1 -1
  79. package/dist/keys-BHhw_0Wh.cjs +2 -0
  80. package/dist/keys-BHhw_0Wh.cjs.map +1 -0
  81. package/dist/keys-D5r_GH9q.js +17 -0
  82. package/dist/keys-D5r_GH9q.js.map +1 -0
  83. package/dist/{library-request-ChCar5F8.js → library-request-BKOcaKtQ.js} +2 -2
  84. package/dist/{library-request-ChCar5F8.js.map → library-request-BKOcaKtQ.js.map} +1 -1
  85. package/dist/{library-request-gMFOCNcn.cjs → library-request-BaZOi4eg.cjs} +2 -2
  86. package/dist/{library-request-gMFOCNcn.cjs.map → library-request-BaZOi4eg.cjs.map} +1 -1
  87. package/dist/{long-frames-Bky6nZDF.cjs → long-frames-CF3qiSAX.cjs} +2 -2
  88. package/dist/long-frames-CF3qiSAX.cjs.map +1 -0
  89. package/dist/{long-frames-DDumopji.js → long-frames-DI5ypfAF.js} +5 -5
  90. package/dist/long-frames-DI5ypfAF.js.map +1 -0
  91. package/dist/models/batch.d.ts +4 -0
  92. package/dist/models/bus.d.ts +32 -9
  93. package/dist/models/config.d.ts +347 -9
  94. package/dist/models/drop.d.ts +1 -1
  95. package/dist/models/health.d.ts +27 -0
  96. package/dist/models/storage.d.ts +13 -0
  97. package/dist/network-CF8UO5PK.cjs +2 -0
  98. package/dist/network-CF8UO5PK.cjs.map +1 -0
  99. package/dist/{network-BsBZ6_-Q.js → network-DdzXDI3J.js} +18 -16
  100. package/dist/network-DdzXDI3J.js.map +1 -0
  101. package/dist/openfin-BwEN0uj4.js.map +1 -1
  102. package/dist/openfin-DtH2f7zX.cjs.map +1 -1
  103. package/dist/{platform-4yYjMD-B.js → platform-Bw1btWCT.js} +16 -10
  104. package/dist/platform-Bw1btWCT.js.map +1 -0
  105. package/dist/platform-DBSKTvFn.cjs +2 -0
  106. package/dist/platform-DBSKTvFn.cjs.map +1 -0
  107. package/dist/{remote-rules-1KqfVBIu.js → remote-rules-DIcC5vVC.js} +3 -3
  108. package/dist/{remote-rules-1KqfVBIu.js.map → remote-rules-DIcC5vVC.js.map} +1 -1
  109. package/dist/{remote-rules-BHgEGlYi.cjs → remote-rules-DpFmOef2.cjs} +2 -2
  110. package/dist/{remote-rules-BHgEGlYi.cjs.map → remote-rules-DpFmOef2.cjs.map} +1 -1
  111. package/dist/sampling-BVjspJWu.cjs +2 -0
  112. package/dist/sampling-BVjspJWu.cjs.map +1 -0
  113. package/dist/{sampling-nYIWP_vP.js → sampling-Cm3WhI0a.js} +26 -36
  114. package/dist/sampling-Cm3WhI0a.js.map +1 -0
  115. package/dist/{sanitize-BiUKCUG6.js → sanitize-C-ahCFsG.js} +2 -2
  116. package/dist/{sanitize-BiUKCUG6.js.map → sanitize-C-ahCFsG.js.map} +1 -1
  117. package/dist/{sanitize-BxuPSXOk.cjs → sanitize-DHucKGdi.cjs} +2 -2
  118. package/dist/{sanitize-BxuPSXOk.cjs.map → sanitize-DHucKGdi.cjs.map} +1 -1
  119. package/dist/sender-D3fRCR8d.cjs +3 -0
  120. package/dist/sender-D3fRCR8d.cjs.map +1 -0
  121. package/dist/sender-DUUmSglb.js +1163 -0
  122. package/dist/sender-DUUmSglb.js.map +1 -0
  123. package/dist/storage/context-storage.d.ts +89 -0
  124. package/dist/storage/emergency-queue.d.ts +9 -1
  125. package/dist/storage/factory.d.ts +7 -1
  126. package/dist/storage/idb-driver.d.ts +13 -0
  127. package/dist/storage/indexeddb-storage.d.ts +13 -0
  128. package/dist/storage/local-storage.d.ts +21 -1
  129. package/dist/storage/memory-storage.d.ts +13 -0
  130. package/dist/storage-BA9RqRO-.cjs +2 -0
  131. package/dist/storage-BA9RqRO-.cjs.map +1 -0
  132. package/dist/storage-w7Tslvlq.js +17 -0
  133. package/dist/storage-w7Tslvlq.js.map +1 -0
  134. package/dist/storm-CNZjsw4T.cjs +2 -0
  135. package/dist/storm-CNZjsw4T.cjs.map +1 -0
  136. package/dist/storm-Daq2jGHU.js +10 -0
  137. package/dist/storm-Daq2jGHU.js.map +1 -0
  138. package/dist/transport/retry-engine.d.ts +7 -2
  139. package/dist/transport/status-transport.d.ts +17 -0
  140. package/dist/types-BR9t_w28.js.map +1 -1
  141. package/dist/types-C7WNpnG1.cjs.map +1 -1
  142. package/dist/utils/fixed-window.d.ts +9 -0
  143. package/dist/utils/identity.d.ts +9 -2
  144. package/dist/utils/lock.d.ts +8 -0
  145. package/dist/utils/openfin.d.ts +1 -1
  146. package/dist/utils/platform.d.ts +3 -1
  147. package/dist/web-socket-BacvKOvD.cjs +2 -0
  148. package/dist/web-socket-BacvKOvD.cjs.map +1 -0
  149. package/dist/web-socket-CpsD8WAa.js +105 -0
  150. package/dist/web-socket-CpsD8WAa.js.map +1 -0
  151. package/package.json +1 -1
  152. package/dist/batch-C4oF6XZT.cjs +0 -2
  153. package/dist/batch-C4oF6XZT.cjs.map +0 -1
  154. package/dist/batch-D-4xl7op.js.map +0 -1
  155. package/dist/bus-Cyvq-Ngx.js +0 -478
  156. package/dist/bus-Cyvq-Ngx.js.map +0 -1
  157. package/dist/bus-rOhVuRee.cjs +0 -2
  158. package/dist/bus-rOhVuRee.cjs.map +0 -1
  159. package/dist/console-BT7mcgU6.js.map +0 -1
  160. package/dist/console-Boqa7new.cjs.map +0 -1
  161. package/dist/constants-BgRS6MB0.cjs +0 -2
  162. package/dist/constants-BgRS6MB0.cjs.map +0 -1
  163. package/dist/constants-L_d5YvvQ.js +0 -160
  164. package/dist/constants-L_d5YvvQ.js.map +0 -1
  165. package/dist/errors-BDI96zKc.js.map +0 -1
  166. package/dist/errors-_xEsCVXn.cjs +0 -3
  167. package/dist/errors-_xEsCVXn.cjs.map +0 -1
  168. package/dist/fixed-window-BR0bu32Y.cjs +0 -2
  169. package/dist/fixed-window-BR0bu32Y.cjs.map +0 -1
  170. package/dist/fixed-window-Re7jIRJH.js +0 -9
  171. package/dist/fixed-window-Re7jIRJH.js.map +0 -1
  172. package/dist/identity-Bwku7zzN.cjs +0 -2
  173. package/dist/identity-Bwku7zzN.cjs.map +0 -1
  174. package/dist/identity-Dtv917nz.js +0 -98
  175. package/dist/identity-Dtv917nz.js.map +0 -1
  176. package/dist/indexeddb-storage-Cvavrf-y.cjs +0 -2
  177. package/dist/indexeddb-storage-Cvavrf-y.cjs.map +0 -1
  178. package/dist/indexeddb-storage-HgkQUTyS.js.map +0 -1
  179. package/dist/interactions-Bhe1ft8P.cjs +0 -2
  180. package/dist/interactions-Bhe1ft8P.cjs.map +0 -1
  181. package/dist/interactions-Ck01cEij.js.map +0 -1
  182. package/dist/log-record-cwFiLyPY.js +0 -17
  183. package/dist/log-record-cwFiLyPY.js.map +0 -1
  184. package/dist/log-record-jX9eWUP8.cjs +0 -2
  185. package/dist/log-record-jX9eWUP8.cjs.map +0 -1
  186. package/dist/long-frames-Bky6nZDF.cjs.map +0 -1
  187. package/dist/long-frames-DDumopji.js.map +0 -1
  188. package/dist/network-BsBZ6_-Q.js.map +0 -1
  189. package/dist/network-_4csBGBM.cjs +0 -2
  190. package/dist/network-_4csBGBM.cjs.map +0 -1
  191. package/dist/platform-4yYjMD-B.js.map +0 -1
  192. package/dist/platform-o7r1ocOu.cjs +0 -2
  193. package/dist/platform-o7r1ocOu.cjs.map +0 -1
  194. package/dist/sampling-C4my-ma0.cjs +0 -2
  195. package/dist/sampling-C4my-ma0.cjs.map +0 -1
  196. package/dist/sampling-nYIWP_vP.js.map +0 -1
  197. package/dist/sender-6vrT9fFL.cjs +0 -3
  198. package/dist/sender-6vrT9fFL.cjs.map +0 -1
  199. package/dist/sender-DFQMF39P.js +0 -1351
  200. package/dist/sender-DFQMF39P.js.map +0 -1
  201. package/dist/storm-6YYbXzT_.cjs +0 -2
  202. package/dist/storm-6YYbXzT_.cjs.map +0 -1
  203. package/dist/storm-CfO0Sam2.js +0 -10
  204. package/dist/storm-CfO0Sam2.js.map +0 -1
  205. package/dist/web-socket-Ar4cZxmd.js +0 -102
  206. package/dist/web-socket-Ar4cZxmd.js.map +0 -1
  207. package/dist/web-socket-BwJdwSHl.cjs +0 -2
  208. package/dist/web-socket-BwJdwSHl.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"log-record-cwFiLyPY.js","names":["LEVEL_ORDER","nowUnixNano","isLogLevel","value","isLogRecord","record"],"sources":["../src/models/log-record.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\nimport { LEVEL_ORDER } from \"../constants\";\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing that a record tells about. `action` is something that a person did.\n * `event` is something that the application did. `metric` is a measurement.\n * `log` is a log call of the application. `system` is the output of this library.\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"log\" | \"system\" | \"span\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks if a value is a known log level. An own-key check rejects \"toString\".\n * @param value The value to check.\n * @returns True if `value` is a key of the severity table.\n */\nexport function isLogLevel(value: unknown): value is LogLevel {\n return typeof value === \"string\" && Object.hasOwn(LEVEL_ORDER, value);\n}\n\n/**\n * Checks if a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns True if `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n"],"mappings":";;AA0DA,SAAgBC,IAAsB;CACpC,OAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE;AAC/B;AAOA,SAAgBC,EAAW,GAAmC;CAC5D,OAAO,OAAOC,KAAU,YAAY,OAAO,OAAOH,GAAaG,CAAK;AACtE;AAUA,SAAgBC,EAAY,GAAoC;CAC9D,IAAI,OAAOD,KAAU,aAAYA,GAC/B,OAAO;CAIT,IAAME,IAASF;CACf,OACE,OAAOE,EAAO,QAAS,YACvB,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,cAAe,YAC7BA,EAAO,eAAe,QACtB,OAAOA,EAAO,YAAa,YAC3BA,EAAO,aAAa;AAExB"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-BgRS6MB0.cjs");function t(){return`${String(Date.now())}000000`}function n(t){return typeof t==`string`&&Object.hasOwn(e.pt,t)}function r(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.body==`string`&&typeof t.severityText==`string`&&typeof t.timeUnixNano==`string`&&typeof t.attributes==`object`&&t.attributes!==null&&typeof t.resource==`object`&&t.resource!==null}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return n}});
2
- //# sourceMappingURL=log-record-jX9eWUP8.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"log-record-jX9eWUP8.cjs","names":["LEVEL_ORDER","require_constants","nowUnixNano","isLogLevel","value","isLogRecord","record"],"sources":["../src/models/log-record.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\nimport { LEVEL_ORDER } from \"../constants\";\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing that a record tells about. `action` is something that a person did.\n * `event` is something that the application did. `metric` is a measurement.\n * `log` is a log call of the application. `system` is the output of this library.\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"log\" | \"system\" | \"span\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks if a value is a known log level. An own-key check rejects \"toString\".\n * @param value The value to check.\n * @returns True if `value` is a key of the severity table.\n */\nexport function isLogLevel(value: unknown): value is LogLevel {\n return typeof value === \"string\" && Object.hasOwn(LEVEL_ORDER, value);\n}\n\n/**\n * Checks if a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns True if `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n"],"mappings":"4CA0DA,SAAgBE,GAAsB,CACpC,MAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE,OAC/B,CAOA,SAAgBC,EAAW,EAAmC,CAC5D,OAAO,OAAOC,GAAU,UAAY,OAAO,OAAOJ,EAAAA,GAAaI,CAAK,CACtE,CAUA,SAAgBC,EAAY,EAAoC,CAC9D,GAAI,OAAOD,GAAU,WAAYA,EAC/B,MAAO,GAIT,IAAME,EAASF,EACf,OACE,OAAOE,EAAO,MAAS,UACvB,OAAOA,EAAO,cAAiB,UAC/B,OAAOA,EAAO,cAAiB,UAC/B,OAAOA,EAAO,YAAe,UAC7BA,EAAO,aAAe,MACtB,OAAOA,EAAO,UAAa,UAC3BA,EAAO,WAAa,IAExB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"long-frames-Bky6nZDF.cjs","names":["allowInWindow","recordedUrl","require_platform","require_storm","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if you set fullUrls.\n const url = (value: string): string => recordedUrl(value, this.ctx.config.capture.fullUrls);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":"6EAWA,IAAMI,EAAc,CAAC,uBAAwB,UAAU,EAyBvD,SAASC,EAAc,EAA6D,CAClF,IAAIC,EAEJ,IAAK,IAAMC,KAAUC,GAAW,CAAC,GAC3B,CAACF,GAAWC,EAAO,SAAWD,EAAQ,YACxC,EAAUC,GAId,OAAOD,CACT,CAGA,IAAaG,EAAb,KAAiD,CAgBlB,IAd7B,KAAgB,cAGhB,SAGA,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAG5D,UAAA,IAKA,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACd,GAAI,KAAK,SACP,OAKF,GAAM,CAAE,QAAS,KAAK,IAChBC,EAAQ,CAACC,EAAK,WACpB,EAAK,WAAa,GAGlB,IAAMC,EACJ,OAAO,oBAAwB,IAC3B,IAAA,GACA,oBAAoB,oBACpBC,EAAOV,EAAY,KAAM,GAASS,GAAW,SAASE,CAAI,CAAC,EAEjE,GAAID,IAAS,IAAA,GAAW,CACtB,GAAI,CAACH,EACH,OAGF,KAAK,IAAI,YAAY,OACnB,yBACA,yEACF,CAEF,KAEA,MAAK,UAAY,KAAK,cAAc,EACpC,KAAK,SAAW,IAAI,oBAAqB,GAAS,CAChD,IAAK,IAAMK,KAASC,EAAK,WAAW,EAClC,KAAK,OAAOD,CAAK,CAErB,CAAC,EAGD,KAAK,SAAS,QAAQ,CAAE,OAAM,SAAUL,CAAM,CAAC,CACjD,CAGA,WAAkB,CAChB,KAAK,UAAU,WAAW,EAC1B,KAAK,SAAW,IAAA,EAClB,CAMA,eAAgC,CAC9B,IAAMO,EAAiB,KAAK,IAAI,OAAO,QAAQ,qBAU/C,OARI,OAAOA,GAAU,UAAY,OAAO,SAASA,CAAK,GAAKA,GAAS,EAC3DA,GAGT,KAAK,IAAI,YAAY,OACnB,iBACA,mFACF,EACA,IACF,CAMA,OAAe,EAAyB,CACtC,GAAIF,EAAM,SAAW,KAAK,UACxB,OAGF,GAAM,CAAE,eAAgB,KAAK,IAE7B,GAAI,CAAChB,EAAAA,EAAc,KAAK,OAAA,GAAmCmB,EAAa,aAAa,EACnF,OAGF,IAAMC,EAAW,KAAK,MAAMJ,EAAM,QAAQ,EACpCK,EAAiC,CAAE,aAAcL,EAAM,SAAU,EAEnEA,EAAM,mBAAqB,IAAA,KAC7B,EAAM,qBAAuB,KAAK,MAAMA,EAAM,gBAAgB,GAGhE,IAAMT,EAASF,EAAcW,EAAM,OAAO,EAGpCM,EAAO,GAA0BrB,EAAAA,EAAYiB,EAAO,KAAK,IAAI,OAAO,QAAQ,QAAQ,EAE1F,GAAIX,GAAQ,QAAS,CAGnB,GAAM,CAAE,WAAYA,EACpB,EAAM,wBAA0BgB,EAAQ,SAAS,KAAK,EAAID,EAAIC,CAAO,EAAIA,CAC3E,CAEIhB,GAAQ,YACV,EAAM,uBAAyBe,EAAIf,EAAO,SAAS,GAGrD,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,QACV,QAAS,cAAc,OAAOa,CAAQ,EAAE,IAC1C,CAAC,EACD,KAAK,IAAI,OAAO,UAAU,yBAA0BA,EAAU,KAAM,YAAaC,CAAK,CACxF,CACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"long-frames-DDumopji.js","names":["recordedUrl","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","allowInWindow","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if you set fullUrls.\n const url = (value: string): string => recordedUrl(value, this.ctx.config.capture.fullUrls);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":";;;AAWA,IAAMC,IAAc,CAAC,wBAAwB,UAAU;AAyBvD,SAASC,EAAc,GAA6D;CAClF,IAAIC;CAEJ,KAAK,IAAMC,KAAUC,KAAW,CAAC,GAC/B,CAAI,CAACF,KAAWC,EAAO,WAAWD,EAAQ,cACxC,IAAUC;CAId,OAAOD;AACT;AAGA,IAAaG,IAAb,MAAiD;CAgBlB;CAd7B,OAAgB;CAGhB;CAGA,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAG5D,YAAA;CAKA,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,IAAI,KAAK,UACP;EAKF,IAAM,EAAE,YAAS,KAAK,KAChBC,IAAQ,CAACC,EAAK;EACpB,EAAK,aAAa;EAGlB,IAAMC,IACJ,OAAO,sBAAwB,MAC3B,KAAA,IACA,oBAAoB,qBACpBC,IAAOV,EAAY,MAAM,MAASS,GAAW,SAASE,CAAI,CAAC;EAEjE,IAAID,MAAS,KAAA,GAAW;GACtB,IAAI,CAACH,GACH;GAGF,KAAK,IAAI,YAAY,OACnB,0BACA,yEACF;EAEF,OAUA,AARA,KAAK,YAAY,KAAK,cAAc,GACpC,KAAK,WAAW,IAAI,qBAAqB,MAAS;GAChD,KAAK,IAAMK,KAASC,EAAK,WAAW,GAClC,KAAK,OAAOD,CAAK;EAErB,CAAC,GAGD,KAAK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_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","url","status","name","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","plan","durationMs","call","original","startedAt","response","read","trace","injected","headers","key","value","ignored","propagates","meta","proto","restoreOpen","rest","originalOpen","restoreSend","args","addTraceHeaders","originalSend","span","endMs","rounded"],"sources":["../src/capture/network.ts"],"sourcesContent":["// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { isLibraryRequest, isTransportPending } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { ClientSpan } from \"../utils/tracing\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Milliseconds in one second. The histogram is in seconds, as the OpenTelemetry name gives. */\nconst MS_PER_SECOND = 1000;\n\n/**\n * The HTTP client duration histogram of the OpenTelemetry semantic conventions. Its boundaries\n * are the ones that the conventions advise.\n */\nconst HTTP_DURATION: InstrumentDef = {\n name: \"http.client.request.duration\",\n kind: \"histogram\",\n unit: \"s\",\n boundaries: [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n};\n\n/**\n * Gives the low-cardinality attributes of one request. The path and the query stay out. Each\n * value of an attribute makes a new series in the backend.\n * @param method Uppercase HTTP method.\n * @param url Request URL.\n * @param status HTTP status code, or 0 when no response came.\n * @param error Failure of a request without a response.\n * @returns The attribute set.\n */\nfunction durationAttributes(\n method: string,\n url: string,\n status: number,\n error: unknown,\n): MetricAttributes {\n // A relative URL needs the page URL as its base. A worker has a location too.\n const base = typeof location !== \"undefined\" ? location.href : undefined;\n const attributes: MetricAttributes = {\n \"http.request.method\": method,\n \"server.address\": new URL(url, base).hostname,\n };\n\n if (status === 0) {\n // A request without a response has the type of its error, for example TypeError.\n const name = isErrorLike(error) ? error.name : \"\";\n attributes[\"error.type\"] = name === \"\" ? \"_OTHER\" : name;\n return attributes;\n }\n\n attributes[\"http.response.status_code\"] = status;\n if (status >= 400) {\n attributes[\"error.type\"] = String(status);\n }\n\n return attributes;\n}\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n /** Client span that the traceparent names. */\n span?: ClientSpan;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n /** Client span that the traceparent names. */\n span?: ClientSpan;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** True after the report of a request during a custom transport call. It reports one time. */\n private warnedTransport = false;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (plan: FetchPlan, status: number, durationMs: number, error: unknown): void => {\n this.record(plan.method, plan.url, status, durationMs, error, plan.span);\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = { method, url, input, init };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const trace = this.ctx.tracing.request();\n const injected = Object.entries(trace.headers);\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n\n // Record the client span only for a request that carries its traceparent.\n plan.span = trace.span;\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (meta: XhrMeta, status: number, durationMs: number): void => {\n this.record(meta.method, meta.url, status, durationMs, undefined, meta.span);\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n // A reused XHR gets a new listener at each send. The old one must not fire again.\n this.addEventListener(\n \"loadend\",\n () => {\n record(meta, this.status, performance.now() - meta.startedAt);\n },\n { once: true },\n );\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n meta.span = addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n * @param span Client span that the traceparent of the request names.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n span?: ClientSpan,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = recordedUrl(target, this.ctx.config.capture.fullUrls);\n\n // A request of the transport after an await records a value. That value causes the next send.\n if (!this.warnedTransport && isTransportPending()) {\n this.warnedTransport = true;\n this.ctx.diagnostics.report(\n \"capture.transport_request\",\n `Network capture saw ${method} ${url} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`,\n );\n }\n\n // The histogram has its own guard. A URL that does not parse must not stop the record.\n if (this.ctx.config.capture.httpMetrics) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the duration of ${method} ${url}.`,\n () => {\n const attributes = durationAttributes(method, target, status, error);\n this.ctx.recordMetric(HTTP_DURATION, durationMs / MS_PER_SECOND, attributes);\n },\n );\n }\n\n if (span) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the span of ${method} ${url}.`,\n () => {\n const endMs = Date.now();\n this.ctx.recordSpan({\n ...span,\n name: method,\n kind: \"client\",\n startMs: endMs - durationMs,\n endMs,\n error: status === 0 || status >= 400,\n attributes: { ...durationAttributes(method, target, status, error), \"url.full\": url },\n });\n },\n );\n }\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n * @returns The client span that the traceparent names, or undefined.\n */\nfunction addTraceHeaders(\n xhr: XMLHttpRequest,\n url: string,\n ctx: CaptureContext,\n): ClientSpan | undefined {\n try {\n const trace = ctx.tracing.request();\n for (const [key, value] of Object.entries(trace.headers)) {\n xhr.setRequestHeader(key, value);\n }\n return trace.span;\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n return undefined;\n }\n}\n"],"mappings":";;;;;;AAgBA,IAAMM,IAAgB,KAMhBC,IAA+B;CACnC,MAAM;CACN,MAAM;CACN,MAAM;CACN,YAAY;EAAC;EAAO;EAAM;EAAO;EAAM;EAAO;EAAK;EAAM;EAAK;EAAM;EAAG;EAAK;EAAG;EAAK;CAAE;AACxF;AAWA,SAASC,EACP,GACA,GACA,GACA,GACkB;CAElB,IAAMC,IAAO,OAAO,WAAa,MAAc,SAAS,OAAO,KAAA,GACzDC,IAA+B;EACnC,uBAAuBC;EACvB,kBAAkB,IAAI,IAAIC,GAAKH,CAAI,CAAC,CAAC;CACvC;CAEA,IAAII,MAAW,GAAG;EAEhB,IAAMC,IAAOd,EAAYe,CAAK,IAAIA,EAAM,OAAO;EAE/C,OADA,EAAW,gBAAgBD,MAAS,KAAK,WAAWA,GAC7CJ;CACT;CAOA,OALA,EAAW,+BAA+BG,GACtCA,KAAU,QACZ,EAAW,gBAAgB,OAAOA,CAAM,IAGnCH;AACT;AA0BA,SAASM,IAAyB;CAChC,OAAO,eAAe;AACxB;AAuBA,SAASC,EAAQ,GAAwB;CACvC,IAAI,OAAOC,KAAU,UACnB,OAAOA;CAGT,IAAIA,aAAiB,KACnB,OAAOA,EAAM;CAGf,IAAI,OAAOA,KAAU,YAAYA,GAAgB;EAC/C,IAAM,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CACf,SAASzB,GAAO;EACd,EAAI,YAAY,OACd,yBACA,qFACA,EAAE,OAAI,GACNA,CACF;EACA;CACF;AACF"}
@@ -1,2 +0,0 @@
1
- const e=require("./error-like-gGRx2s36.cjs"),t=require("./library-request-gMFOCNcn.cjs"),n=require("./platform-o7r1ocOu.cjs"),r=require("./patch-BX8KrPCT.cjs"),i=require("./types-C7WNpnG1.cjs");var a=1e3,o={name:`http.client.request.duration`,kind:`histogram`,unit:`s`,boundaries:[.005,.01,.025,.05,.075,.1,.25,.5,.75,1,2.5,5,7.5,10]};function s(t,n,r,i){let a=typeof location<`u`?location.href:void 0,o={"http.request.method":t,"server.address":new URL(n,a).hostname};if(r===0){let t=e.r(i)?i.name:``;return o[`error.type`]=t===``?`_OTHER`:t,o}return o[`http.response.status_code`]=r,r>=400&&(o[`error.type`]=String(r)),o}function c(){return XMLHttpRequest.prototype}function l(e){if(typeof e==`string`)return e;if(e instanceof URL)return e.href;if(typeof e==`object`&&e){let{url:t}=e;if(typeof t==`string`)return t}return String(e)}function u(e,t){let n=t?.method;return n===void 0&&typeof e==`object`&&e&&(n=e.method),f(n??`GET`)}function d(e){return typeof e==`object`&&!(e instanceof URL)&&!(e instanceof Request)}function f(e){return typeof e==`string`?e.toUpperCase():String(e)}var p=class{ctx;name=`network`;installed=!1;restores=[];warnedTransport=!1;constructor(e){this.ctx=e}install(){this.installed||(this.installed=!0,this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr())}uninstall(){if(this.installed){this.installed=!1;for(let e of this.restores.splice(0))e()}}ignored(e){return t.t()||i.t(e,this.ctx.config.capture.ignoreUrls)}propagates(e){let t=this.ctx.config.capture.propagateTraceHeaderTo;if(t.length===0)return!1;let n=this.ctx.diagnostics.guard(`capture.header_failed`,`The library could not read the origin of a request URL. Only a RegExp target can match it.`,()=>new URL(e,location.href).origin);return t.some(t=>typeof t==`string`?t===n:t.test(e))}installFetch(){if(typeof globalThis.fetch!=`function`)return;let e=!0,t=(e,t)=>this.prepareFetch(e,t),n=(e,t,n,r)=>{this.record(e.method,e.url,t,n,r,e.span)},i=r.t(globalThis,`fetch`,r=>{let i=r.bind(globalThis);return async function(r,a){let o=e?t(r,a):void 0;if(!o)return i(r,a);let s=performance.now();try{let e=await i(o.input,o.init);return n(o,e.status,performance.now()-s,void 0),e}catch(e){throw n(o,0,performance.now()-s,e),e}}});this.restores.push(()=>{e=!1,i()})}prepareFetch(e,t){let n=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read a fetch request. It sends the request unchanged.`,()=>{let n=l(e);if(!this.ignored(n))return{method:u(e,t),url:n,propagate:this.propagates(n)}});if(!n)return;let{method:r,url:i}=n,a={method:r,url:i,input:e,init:t};if(!n.propagate||d(e))return a;try{let n=this.ctx.tracing.request(),r=Object.entries(n.headers);if(e instanceof Request){let t=new Headers(e.headers);for(let[e,n]of r)t.set(e,n);a.input=new Request(e,{headers:t})}else{let e=new Headers(t?.headers);for(let[t,n]of r)e.set(t,n);a.init={...t,headers:e}}a.span=n.span}catch(n){a.input=e,a.init=t,this.ctx.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:i},n)}return a}installXhr(){if(typeof XMLHttpRequest>`u`)return;let e=!0,t=this.ctx,n=e=>this.ignored(e),i=e=>this.propagates(e),a=(e,t,n)=>{this.record(e.method,e.url,t,n,void 0,e.span)},o=c(),s=r.t(o,`open`,n=>function(r,i,...a){e&&t.diagnostics.guard(`capture.record_failed`,`The library could not read an XMLHttpRequest. It does not record the request.`,()=>{this.__uiobs={method:f(r),url:l(i),startedAt:0}}),n.apply(this,[r,i,...a])}),u=r.t(o,`send`,r=>function(...o){let s=e?this.__uiobs:void 0;s&&t.diagnostics.guard(`capture.record_failed`,`The library could not record ${s.method} ${s.url}.`,()=>{n(s.url)||(s.startedAt=performance.now(),this.addEventListener(`loadend`,()=>{a(s,this.status,performance.now()-s.startedAt)},{once:!0}),i(s.url)&&(s.span=m(this,s.url,t)))}),r.apply(this,o)});this.restores.push(()=>{e=!1,s(),u()})}record(e,r,i,c,l,u){let d=n.i(r,this.ctx.config.capture.fullUrls);!this.warnedTransport&&t.n()&&(this.warnedTransport=!0,this.ctx.diagnostics.report(`capture.transport_request`,`Network capture saw ${e} ${d} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`)),this.ctx.config.capture.httpMetrics&&this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record the duration of ${e} ${d}.`,()=>{let t=s(e,r,i,l);this.ctx.recordMetric(o,c/a,t)}),u&&this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record the span of ${e} ${d}.`,()=>{let t=Date.now();this.ctx.recordSpan({...u,name:e,kind:`client`,startMs:t-c,endMs:t,error:i===0||i>=400,attributes:{...s(e,r,i,l),"url.full":d}})}),this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record ${e} ${d}.`,()=>{let t=Math.round(c);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${e} ${d} ${i===0?`failed`:String(i)}`,data:{durationMs:t}});let n={"http.request.method":e,"url.full":d,"http.response.status_code":i,"http.duration_ms":t};i===0?this.ctx.logger.error(`${e} ${d} failed`,l,n):i>=400?this.ctx.logger.warn(`${e} ${d} returned ${String(i)}`,n):this.ctx.logger.debug(`${e} ${d}`,n)})}};function m(e,t,n){try{let t=n.tracing.request();for(let[n,r]of Object.entries(t.headers))e.setRequestHeader(n,r);return t.span}catch(e){n.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:t},e);return}}exports.NetworkCapture=p;
2
- //# sourceMappingURL=network-_4csBGBM.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"network-_4csBGBM.cjs","names":["isErrorLike","isLibraryRequest","matchesAny","patch","recordedUrl","isTransportPending","require_error_like","require_library_request","require_platform","require_patch","require_types","MS_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","url","status","name","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","plan","durationMs","call","original","startedAt","response","read","trace","injected","headers","key","value","ignored","propagates","meta","proto","restoreOpen","rest","originalOpen","restoreSend","args","addTraceHeaders","originalSend","span","endMs","rounded","xhr"],"sources":["../src/capture/network.ts"],"sourcesContent":["// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { isLibraryRequest, isTransportPending } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { ClientSpan } from \"../utils/tracing\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Milliseconds in one second. The histogram is in seconds, as the OpenTelemetry name gives. */\nconst MS_PER_SECOND = 1000;\n\n/**\n * The HTTP client duration histogram of the OpenTelemetry semantic conventions. Its boundaries\n * are the ones that the conventions advise.\n */\nconst HTTP_DURATION: InstrumentDef = {\n name: \"http.client.request.duration\",\n kind: \"histogram\",\n unit: \"s\",\n boundaries: [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n};\n\n/**\n * Gives the low-cardinality attributes of one request. The path and the query stay out. Each\n * value of an attribute makes a new series in the backend.\n * @param method Uppercase HTTP method.\n * @param url Request URL.\n * @param status HTTP status code, or 0 when no response came.\n * @param error Failure of a request without a response.\n * @returns The attribute set.\n */\nfunction durationAttributes(\n method: string,\n url: string,\n status: number,\n error: unknown,\n): MetricAttributes {\n // A relative URL needs the page URL as its base. A worker has a location too.\n const base = typeof location !== \"undefined\" ? location.href : undefined;\n const attributes: MetricAttributes = {\n \"http.request.method\": method,\n \"server.address\": new URL(url, base).hostname,\n };\n\n if (status === 0) {\n // A request without a response has the type of its error, for example TypeError.\n const name = isErrorLike(error) ? error.name : \"\";\n attributes[\"error.type\"] = name === \"\" ? \"_OTHER\" : name;\n return attributes;\n }\n\n attributes[\"http.response.status_code\"] = status;\n if (status >= 400) {\n attributes[\"error.type\"] = String(status);\n }\n\n return attributes;\n}\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n /** Client span that the traceparent names. */\n span?: ClientSpan;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n /** Client span that the traceparent names. */\n span?: ClientSpan;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** True after the report of a request during a custom transport call. It reports one time. */\n private warnedTransport = false;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (plan: FetchPlan, status: number, durationMs: number, error: unknown): void => {\n this.record(plan.method, plan.url, status, durationMs, error, plan.span);\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = { method, url, input, init };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const trace = this.ctx.tracing.request();\n const injected = Object.entries(trace.headers);\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n\n // Record the client span only for a request that carries its traceparent.\n plan.span = trace.span;\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (meta: XhrMeta, status: number, durationMs: number): void => {\n this.record(meta.method, meta.url, status, durationMs, undefined, meta.span);\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n // A reused XHR gets a new listener at each send. The old one must not fire again.\n this.addEventListener(\n \"loadend\",\n () => {\n record(meta, this.status, performance.now() - meta.startedAt);\n },\n { once: true },\n );\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n meta.span = addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n * @param span Client span that the traceparent of the request names.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n span?: ClientSpan,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = recordedUrl(target, this.ctx.config.capture.fullUrls);\n\n // A request of the transport after an await records a value. That value causes the next send.\n if (!this.warnedTransport && isTransportPending()) {\n this.warnedTransport = true;\n this.ctx.diagnostics.report(\n \"capture.transport_request\",\n `Network capture saw ${method} ${url} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`,\n );\n }\n\n // The histogram has its own guard. A URL that does not parse must not stop the record.\n if (this.ctx.config.capture.httpMetrics) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the duration of ${method} ${url}.`,\n () => {\n const attributes = durationAttributes(method, target, status, error);\n this.ctx.recordMetric(HTTP_DURATION, durationMs / MS_PER_SECOND, attributes);\n },\n );\n }\n\n if (span) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the span of ${method} ${url}.`,\n () => {\n const endMs = Date.now();\n this.ctx.recordSpan({\n ...span,\n name: method,\n kind: \"client\",\n startMs: endMs - durationMs,\n endMs,\n error: status === 0 || status >= 400,\n attributes: { ...durationAttributes(method, target, status, error), \"url.full\": url },\n });\n },\n );\n }\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n * @returns The client span that the traceparent names, or undefined.\n */\nfunction addTraceHeaders(\n xhr: XMLHttpRequest,\n url: string,\n ctx: CaptureContext,\n): ClientSpan | undefined {\n try {\n const trace = ctx.tracing.request();\n for (const [key, value] of Object.entries(trace.headers)) {\n xhr.setRequestHeader(key, value);\n }\n return trace.span;\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n return undefined;\n }\n}\n"],"mappings":"kMAgBA,IAAMW,EAAgB,IAMhBC,EAA+B,CACnC,KAAM,+BACN,KAAM,YACN,KAAM,IACN,WAAY,CAAC,KAAO,IAAM,KAAO,IAAM,KAAO,GAAK,IAAM,GAAK,IAAM,EAAG,IAAK,EAAG,IAAK,EAAE,CACxF,EAWA,SAASC,EACP,EACA,EACA,EACA,EACkB,CAElB,IAAMC,EAAO,OAAO,SAAa,IAAc,SAAS,KAAO,IAAA,GACzDC,EAA+B,CACnC,sBAAuBC,EACvB,iBAAkB,IAAI,IAAIC,EAAKH,CAAI,CAAC,CAAC,QACvC,EAEA,GAAII,IAAW,EAAG,CAEhB,IAAMC,EAAOnB,EAAAA,EAAYoB,CAAK,EAAIA,EAAM,KAAO,GAE/C,MADA,GAAW,cAAgBD,IAAS,GAAK,SAAWA,EAC7CJ,CACT,CAOA,MALA,GAAW,6BAA+BG,EACtCA,GAAU,MACZ,EAAW,cAAgB,OAAOA,CAAM,GAGnCH,CACT,CA0BA,SAASM,GAAyB,CAChC,OAAO,eAAe,SACxB,CAuBA,SAASC,EAAQ,EAAwB,CACvC,GAAI,OAAOC,GAAU,SACnB,OAAOA,EAGT,GAAIA,aAAiB,IACnB,OAAOA,EAAM,KAGf,GAAI,OAAOA,GAAU,UAAYA,EAAgB,CAC/C,GAAM,CAAE,OAAQA,EAChB,GAAI,OAAON,GAAQ,SACjB,OAAOA,CAEX,CAGA,OAAO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ACA,MACF,CACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"platform-4yYjMD-B.js","names":["OPENFIN_UA_PATTERN","MOBILE_UA_PATTERN","MACINTOSH_UA_PATTERN","IOS_DEVICE_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","getFin","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","USER_INFO_PATTERN","recordedUrl","bare","url","fullUrls","stripUrlQuery","cut","isOnline"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. The module caches the result. The result does not change during\n// the life of a realm. A webview is also a browser. Test for a webview first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { getFin } from \"./openfin\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** True if the code runs in a worker realm. */\n isWorker: boolean;\n /** True if this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Tests if globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = getFin()?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"The library could not read fin.me.identity.\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(diagnostics),\n };\n return cached;\n}\n\n/**\n * Tests if a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Tests if the current window is the top-level browsing context.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of window.top.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(diagnostics: Diagnostics): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n // A cross-origin parent blocks the read. That proves a frame. Count it. Do not report it.\n diagnostics.count(\"platform.api_blocked\");\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of location.href.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(diagnostics: Diagnostics): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n // A sandbox can block the read. Count the fault. A report on each record is noise.\n diagnostics.count(\"platform.api_blocked\");\n return \"\";\n }\n}\n\n/** Matches the user info of an absolute URL, for example \"user:pass@\". */\nconst USER_INFO_PATTERN = /^([a-z][a-z\\d+.-]*:\\/\\/)[^/?#]*@/i;\n\n/**\n * Gives the form of a URL that the library records. It always removes the user info, which is a\n * credential. Without fullUrls, it also removes the query and the fragment.\n * @param url Absolute or relative URL.\n * @param fullUrls Value of `capture.fullUrls`.\n * @returns The URL to record.\n */\nexport function recordedUrl(url: string, fullUrls: boolean): string {\n const bare = url.replace(USER_INFO_PATTERN, \"$1\");\n return fullUrls ? bare : stripUrlQuery(bare);\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * It cuts the string and does not parse a URL. A relative request target has no base URL.\n * @param url Absolute or relative URL.\n * @returns The URL up to the first \"?\" or \"#\".\n */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n/**\n * Tests if the browser can reach the network. A host without navigator.onLine counts as online.\n * @returns False only when navigator.onLine is false.\n */\nexport function isOnline(): boolean {\n return (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine !== false;\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":";;;AAkDA,IAAIM,IAAkC;AAWtC,SAASC,EAAc,GAAW,GAAuB;CACvD,IAAMC,IAAQC,EAAEC;CAIhB,OAHIF,MAAU,KAAA,KAGPC,aAAcD;AACvB;AAOA,SAAgBG,EAAe,GAA4C;CACzE,IAAIL,GACF,OAAOA;CAET,IAAMG,IAAI,YAEJG,IAAMH,EAAE,WAAqC,aAAa,IAC5DI,IAAyB,WACzBC,GACAC,GACAC,IAAW,IAETC,IAAQZ,EAAO,CAAC,EAAE;CAkCxB,OAhCIE,EAAcE,GAAG,0BAA0B,KAC7C,IAAW,kBACX,IAAW,MACFF,EAAcE,GAAG,yBAAyB,KACnD,IAAW,iBACX,IAAW,MACFF,EAAcE,GAAG,mBAAmB,KAC7C,IAAW,cACX,IAAW,MACFQ,MAAU,KAAA,IAOVR,EAAE,cAAc,KAAA,KAAaA,EAAE,UAAU,KAAA,IAClD,IAAW,UACFA,EAAE,YAAY,KAAA,KAAaS,EAAUN,CAAE,IAChD,IAAW,mBACF,OAAO,WAAa,OAAe,OAAO,UAAY,QAC/D,IAAW,WAXX,IAAWZ,EAAmB,KAAKY,CAAE,IAAI,YAAY,eACrDO,EAAY,MAAM,uBAAuB,qDAAqD;EAC5F,IAAMC,IAAWH,EAAM;EAEvB,AADA,IAAcG,GAAU,MACxB,IAAcA,GAAU;CAC1B,CAAC,IASH,IAAS;EACP;EACA;EACA;EACA,WAAWR;EACX;EACA,oBAAoBS,EAAWF,CAAW;CAC5C,GACOb;AACT;AAOA,SAASY,EAAU,GAAqB;CAMtC,OALId,EAA2B,KAAKQ,CAAE,IAC7B,MAGPT,EAAsB,KAAKS,CAAE,KAAMV,EAAqB,KAAKU,CAAE,KAAKX,EAAkB,KAAKW,CAAE,MACjFA,EAAG,SAAA,aAAwB,KAAK,CAACA,EAAG,SAAA,SAAwB;AAC5E;AAOA,SAAgBS,EAAW,GAAmC;CAC5D,IAAI,OAAO,SAAW,KACpB,OAAO;CAET,IAAI;EACF,OAAO,OAAO,SAAS,OAAO;CAChC,QAAQ;EAGN,OADAF,EAAY,MAAM,sBAAsB,GACjC;CACT;AACF;AAOA,SAAgBG,EAAW,GAAkC;CAC3D,IAAI;EACF,OAAO,OAAO,WAAa,MAAc,SAAS,OAAO;CAC3D,QAAQ;EAGN,OADAH,EAAY,MAAM,sBAAsB,GACjC;CACT;AACF;AAGA,IAAMI,IAAoB;AAS1B,SAAgBC,EAAY,GAAa,GAA2B;CAClE,IAAMC,IAAOC,EAAI,QAAQH,GAAmB,IAAI;CAChD,OAAOI,IAAWF,IAAOG,EAAcH,CAAI;AAC7C;AAQA,SAAgBG,EAAc,GAAqB;CACjD,IAAMC,IAAMH,EAAI,OAAO,MAAM;CAE7B,OAAOG,MAAQ,KAAKH,IAAMA,EAAI,MAAM,GAAGG,CAAG;AAC5C;AAMA,SAAgBC,IAAoB;CAClC,OAAQ,WAAoD,WAAW,WAAW;AACpF"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-BgRS6MB0.cjs"),t=require("./openfin-DtH2f7zX.cjs");var n=null;function r(e,t){let n=e[t];return n!==void 0&&e instanceof n}function i(i){if(n)return n;let s=globalThis,c=s.navigator?.userAgent??``,l=`browser`,u,d,f=!1,p=t.t()?.me;return r(s,`ServiceWorkerGlobalScope`)?(l=`service_worker`,f=!0):r(s,`SharedWorkerGlobalScope`)?(l=`shared_worker`,f=!0):r(s,`WorkerGlobalScope`)?(l=`web_worker`,f=!0):p===void 0?s.Capacitor!==void 0||s.Ionic!==void 0?l=`ionic`:s.cordova!==void 0||a(c)?l=`mobile_webview`:typeof document>`u`&&typeof process<`u`&&(l=`node`):(l=e.At.test(c)?`openfin`:`openfin_web`,i.guard(`openfin.unavailable`,`The library could not read fin.me.identity.`,()=>{let e=p.identity;u=e?.uuid,d=e?.name})),n={platform:l,openfinUuid:u,openfinName:d,userAgent:c,isWorker:f,isTopLevelDocument:o(i)},n}function a(t){return e.t.test(t)?!0:(e.ot.test(t)||e.bt.test(t)&&e.Tt.test(t))&&t.includes(`AppleWebKit`)&&!t.includes(`Safari/`)}function o(e){if(typeof window>`u`)return!1;try{return window.self===window.top}catch{return e.count(`platform.api_blocked`),!1}}function s(e){try{return typeof location<`u`?location.href:``}catch{return e.count(`platform.api_blocked`),``}}var c=/^([a-z][a-z\d+.-]*:\/\/)[^/?#]*@/i;function l(e,t){let n=e.replace(c,`$1`);return t?n:u(n)}function u(e){let t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}function d(){return globalThis.navigator?.onLine!==!1}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
2
- //# sourceMappingURL=platform-o7r1ocOu.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"platform-o7r1ocOu.cjs","names":["getFin","OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","require_constants","require_openfin","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","USER_INFO_PATTERN","recordedUrl","bare","url","fullUrls","stripUrlQuery","cut","isOnline"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. The module caches the result. The result does not change during\n// the life of a realm. A webview is also a browser. Test for a webview first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { getFin } from \"./openfin\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** True if the code runs in a worker realm. */\n isWorker: boolean;\n /** True if this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Tests if globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = getFin()?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"The library could not read fin.me.identity.\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(diagnostics),\n };\n return cached;\n}\n\n/**\n * Tests if a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Tests if the current window is the top-level browsing context.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of window.top.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(diagnostics: Diagnostics): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n // A cross-origin parent blocks the read. That proves a frame. Count it. Do not report it.\n diagnostics.count(\"platform.api_blocked\");\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of location.href.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(diagnostics: Diagnostics): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n // A sandbox can block the read. Count the fault. A report on each record is noise.\n diagnostics.count(\"platform.api_blocked\");\n return \"\";\n }\n}\n\n/** Matches the user info of an absolute URL, for example \"user:pass@\". */\nconst USER_INFO_PATTERN = /^([a-z][a-z\\d+.-]*:\\/\\/)[^/?#]*@/i;\n\n/**\n * Gives the form of a URL that the library records. It always removes the user info, which is a\n * credential. Without fullUrls, it also removes the query and the fragment.\n * @param url Absolute or relative URL.\n * @param fullUrls Value of `capture.fullUrls`.\n * @returns The URL to record.\n */\nexport function recordedUrl(url: string, fullUrls: boolean): string {\n const bare = url.replace(USER_INFO_PATTERN, \"$1\");\n return fullUrls ? bare : stripUrlQuery(bare);\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * It cuts the string and does not parse a URL. A relative request target has no base URL.\n * @param url Absolute or relative URL.\n * @returns The URL up to the first \"?\" or \"#\".\n */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n/**\n * Tests if the browser can reach the network. A host without navigator.onLine counts as online.\n * @returns False only when navigator.onLine is false.\n */\nexport function isOnline(): boolean {\n return (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine !== false;\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":"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AAO,GAET,GAAI,CACF,OAAO,OAAO,OAAS,OAAO,GAChC,MAAQ,CAGN,OADAF,EAAY,MAAM,sBAAsB,EACjC,EACT,CACF,CAOA,SAAgBG,EAAW,EAAkC,CAC3D,GAAI,CACF,OAAO,OAAO,SAAa,IAAc,SAAS,KAAO,EAC3D,MAAQ,CAGN,OADAH,EAAY,MAAM,sBAAsB,EACjC,EACT,CACF,CAGA,IAAMI,EAAoB,oCAS1B,SAAgBC,EAAY,EAAa,EAA2B,CAClE,IAAMC,EAAOC,EAAI,QAAQH,EAAmB,IAAI,EAChD,OAAOI,EAAWF,EAAOG,EAAcH,CAAI,CAC7C,CAQA,SAAgBG,EAAc,EAAqB,CACjD,IAAMC,EAAMH,EAAI,OAAO,MAAM,EAE7B,OAAOG,IAAQ,GAAKH,EAAMA,EAAI,MAAM,EAAGG,CAAG,CAC5C,CAMA,SAAgBC,GAAoB,CAClC,OAAQ,WAAoD,WAAW,SAAW,EACpF"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-BgRS6MB0.cjs"),t=require("./fixed-window-BR0bu32Y.cjs");function n(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function r(e){typeof e!=`number`&&e.unref?.()}var i=class extends Error{constructor(e){super(`The operation took longer than ${String(e)} ms.`),this.name=`DeadlineError`}};function a(e,t){let n,a=new Promise((e,a)=>{let o=setTimeout(()=>{a(new i(t))},t);n=o,r(o)});return Promise.race([e,a]).finally(()=>{clearTimeout(n)})}function o(t){let n=e.q;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.J);return n>>>0}function s(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function c(e,t){let n;for(let[r,i]of Object.entries(t))(e===r||e.startsWith(`${r}.`))&&r.length>(n?.length??-1)&&(n={value:i,length:r.length});return n}function l(e,t){return c(e,t.minLevels)?.value??t.minLevel}function u(e,t,n){let{rates:r,defaultRate:i,remoteMaxRate:a}=t.sampling,o=c(e,r),s=n?c(e,n.rates):void 0;return s&&s.length>=(o?.length??-1)?Math.min(s.value,a):o?o.value:n?.defaultRate===void 0?i:Math.min(n.defaultRate,a)}function d(t,n){return n>=1?!0:n<=0?!1:o(t)/e.En<n}function f(t,n,r){if(t.aggregated===!0||t.type===`span`||t.level===`ERROR`||t.level===`FATAL`||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let i=u(t.namespace,n,r),a=l(t.namespace,n),o=e.pt[t.level]<e.pt[a];return r&&o&&!e.ft.includes(t.type)&&(i=Math.min(i,n.sampling.remoteMaxRate)),d(t.journeyId||t.traceId,i)}function p(t,n,r=null){return f({level:t.severityText,type:s(t,e.d),namespace:s(t,e.n),journeyId:s(t,e.s),traceId:t.traceId,aggregated:s(t,`log.type`)===`metric`&&s(t,e.St.start)!==``},n,r)}var m=class{window={start:0,count:0};allow(n){return n.severityText!==`ERROR`&&n.severityText!==`FATAL`||t.t(this.window,500,e.K)}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return n}});
2
- //# sourceMappingURL=sampling-C4my-ma0.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sampling-C4my-ma0.cjs","names":["FNV_OFFSET_BASIS","FNV_PRIME","UINT32_MAX","LEVEL_ORDER","LEVEL_BYPASS_TYPES","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","METRIC_KEYS","countInWindow","ERROR_STORM_WINDOW_MS","require_constants","require_fixed_window","isObject","value","unrefTimer","timer","DeadlineError","ms","withDeadline","expire","deadline","reject","work","hash","h","i","readAttr","record","key","longestPrefix","best","prefix","values","namespace","levelFor","config","rateFor","local","rates","fromRemote","remote","remoteMaxRate","defaultRate","sampleKey","rate","shouldSampleInput","input","configLevel","belowMinLevel","shouldSample","ErrorCeiling"],"sources":["../src/utils/guards.ts","../src/utils/unref.ts","../src/utils/deadline.ts","../src/core/sampling.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values from outside the library, for example config input, a server answer or\n// the payload of a call.\n\n/**\n * Tests if a value is an object that is not null and not an array.\n * @param value Value to test.\n * @returns True for an object with string keys.\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Timer handle. It is a number in a browser and a Timeout object in Node. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle. A pending timer then does not keep a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. If not, each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record to test.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Value of the longest prefix that matches a namespace. */\ninterface PrefixMatch<T> {\n /** Value of the prefix, for example a rate or a level. */\n value: T;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param values Value for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nexport function longestPrefix<T>(\n namespace: string,\n values: Record<string, T>,\n): PrefixMatch<T> | undefined {\n let best: PrefixMatch<T> | undefined;\n\n for (const [prefix, value] of Object.entries(values)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { value, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the minimum level of a namespace in the config. The longest matching prefix of\n * `minLevels` wins. A namespace with no match uses `minLevel`.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns The minimum level of the namespace.\n */\nexport function levelFor(namespace: string, config: ResolvedConfig): LogLevel {\n return longestPrefix(namespace, config.minLevels)?.value ?? config.minLevel;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate when sampling reads it. A configure() that lowers the cap then applies\n // immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.value, remoteMaxRate);\n }\n\n if (local) {\n return local.value;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/**\n * Decides if sampling keeps a key at a rate. One key always gives the same result.\n * @param key Journey ID or trace ID.\n * @param rate Sampling rate, 0..1.\n * @returns True if sampling keeps the key.\n */\nexport function sampleKey(key: string, rate: number): boolean {\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n /** True for a point of a counter or histogram. A sample of a sum gives a false sum. */\n aggregated?: boolean;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Errors, fatal records and aggregated points bypass sampling filters. The runtime samples a\n // span by its trace before it records the span.\n if (\n input.aggregated === true ||\n input.type === LOG_TYPE_SPAN ||\n input.level === \"ERROR\" ||\n input.level === \"FATAL\"\n ) {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote level adds the records below the config level of the namespace. Cap them too, or they\n // ship at the config rate. The level does not apply to an action or a metric. Do not cap them.\n const configLevel = levelFor(input.namespace, config);\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[configLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n return sampleKey(input.journeyId || input.traceId, rate);\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\n },\n config,\n remote,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** ERROR and FATAL records admitted in the current window. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n return countInWindow(this.window, ERROR_CEILING_MAX_PER_WINDOW, ERROR_STORM_WINDOW_MS);\n }\n}\n"],"mappings":"qFAUA,SAAgBa,EAAS,EAAkD,CACzE,OAAO,OAAOC,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,CCAA,SAAgBC,EAAW,EAA0B,CAC/C,OAAOC,GAAU,UACnBA,EAAM,QAAQ,CAElB,CCRA,IAAaC,EAAb,cAAmC,KAAM,CAIvC,YAAY,EAAY,CACtB,MAAM,kCAAkC,OAAOC,CAAE,EAAE,KAAK,EACxD,KAAK,KAAO,eACd,CACF,EAQA,SAAgBC,EAAgB,EAA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AAO,eAAiB,SAKxDnB,EAAAA,EAAc,KAAK,OAAA,IAAsCC,EAAAA,CAAqB,CACvF,CACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"sampling-nYIWP_vP.js","names":["UINT32_MAX","FNV_PRIME","ERROR_STORM_WINDOW_MS","METRIC_KEYS","ATTR_LOG_TYPE","LEVEL_BYPASS_TYPES","ATTR_APP_NAMESPACE","LEVEL_ORDER","FNV_OFFSET_BASIS","ATTR_JOURNEY_ID","countInWindow","isObject","value","unrefTimer","timer","DeadlineError","ms","withDeadline","expire","deadline","work","hash","h","i","readAttr","record","key","longestPrefix","best","prefix","values","namespace","levelFor","config","rateFor","local","rates","fromRemote","remote","remoteMaxRate","defaultRate","sampleKey","rate","shouldSampleInput","input","configLevel","belowMinLevel","shouldSample","ErrorCeiling"],"sources":["../src/utils/guards.ts","../src/utils/unref.ts","../src/utils/deadline.ts","../src/core/sampling.ts"],"sourcesContent":["// src/utils/guards.ts\n//\n// Type guards for values from outside the library, for example config input, a server answer or\n// the payload of a call.\n\n/**\n * Tests if a value is an object that is not null and not an array.\n * @param value Value to test.\n * @returns True for an object with string keys.\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Timer handle. It is a number in a browser and a Timeout object in Node. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle. A pending timer then does not keep a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. If not, each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n LOG_TYPE_SPAN,\n METRIC_KEYS,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport { countInWindow, type StormWindow } from \"../utils/fixed-window\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record to test.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Value of the longest prefix that matches a namespace. */\ninterface PrefixMatch<T> {\n /** Value of the prefix, for example a rate or a level. */\n value: T;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param values Value for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nexport function longestPrefix<T>(\n namespace: string,\n values: Record<string, T>,\n): PrefixMatch<T> | undefined {\n let best: PrefixMatch<T> | undefined;\n\n for (const [prefix, value] of Object.entries(values)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { value, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the minimum level of a namespace in the config. The longest matching prefix of\n * `minLevels` wins. A namespace with no match uses `minLevel`.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @returns The minimum level of the namespace.\n */\nexport function levelFor(namespace: string, config: ResolvedConfig): LogLevel {\n return longestPrefix(namespace, config.minLevels)?.value ?? config.minLevel;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate when sampling reads it. A configure() that lowers the cap then applies\n // immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.value, remoteMaxRate);\n }\n\n if (local) {\n return local.value;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/**\n * Decides if sampling keeps a key at a rate. One key always gives the same result.\n * @param key Journey ID or trace ID.\n * @param rate Sampling rate, 0..1.\n * @returns True if sampling keeps the key.\n */\nexport function sampleKey(key: string, rate: number): boolean {\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n /** True for a point of a counter or histogram. A sample of a sum gives a false sum. */\n aggregated?: boolean;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Errors, fatal records and aggregated points bypass sampling filters. The runtime samples a\n // span by its trace before it records the span.\n if (\n input.aggregated === true ||\n input.type === LOG_TYPE_SPAN ||\n input.level === \"ERROR\" ||\n input.level === \"FATAL\"\n ) {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote level adds the records below the config level of the namespace. Cap them too, or they\n // ship at the config rate. The level does not apply to an action or a metric. Do not cap them.\n const configLevel = levelFor(input.namespace, config);\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[configLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n return sampleKey(input.journeyId || input.traceId, rate);\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n aggregated:\n readAttr(record, ATTR_LOG_TYPE) === \"metric\" && readAttr(record, METRIC_KEYS.start) !== \"\",\n },\n config,\n remote,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** ERROR and FATAL records admitted in the current window. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n return countInWindow(this.window, ERROR_CEILING_MAX_PER_WINDOW, ERROR_STORM_WINDOW_MS);\n }\n}\n"],"mappings":";;;AAUA,SAAgBW,EAAS,GAAkD;CACzE,OAAO,OAA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gB,EAAO;EAChB,YACED,EAASC,GAAA,UAAqB,MAAM,YAAYD,EAASC,GAAQtB,EAAY,KAAK,MAAM;CAC5F,GACA8B,GACAK,CACF;AACF;AAQA,IAAaU,IAAb,MAA0B;CAExB,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAO5D,MAAM,GAA4B;EAMhC,OALIvB,EAAO,iBAAiB,WAAWA,EAAO,iBAAiB,WAKxDf,EAAc,KAAK,QAAA,KAAsCR,CAAqB;CACvF;AACF"}
@@ -1,3 +0,0 @@
1
- const e=require("./constants-BgRS6MB0.cjs"),t=require("./sampling-C4my-ma0.cjs"),n=require("./log-record-jX9eWUP8.cjs"),r=require("./sanitize-BxuPSXOk.cjs"),i=require("./identity-Bwku7zzN.cjs"),a=require("./library-request-gMFOCNcn.cjs"),o=require("./openfin-DtH2f7zX.cjs"),s=require("./platform-o7r1ocOu.cjs"),c=require("./batch-C4oF6XZT.cjs"),l=require("./remote-rules-BHgEGlYi.cjs");function u(e){let{maxBatches:t}=e;return e.mode===`until-delivered`?{maxBatches:t,maxAgeMs:1/0,maxAttempts:1/0}:{maxBatches:t,maxAgeMs:e.maxAgeMs,maxAttempts:e.maxAttempts}}function d(e,t,n,{skipIfBusy:r=!0}={}){let i=globalThis.navigator?.locks;return i?.request?t.guardAsync(`storage.degraded`,`The library could not get the lock ${e}.`,()=>i.request(e,{ifAvailable:r},e=>e?n():Promise.resolve(void 0))):n()}function f(e,t){return`${e}${String(t.createdAt).padStart(14,`0`)}.${t.id}`}function p(e,t){let n=[];return t.guard(`storage.unavailable`,`The library could not list the localStorage keys.`,()=>{for(let t=0;t<localStorage.length;t++){let r=String(localStorage.key(t));r.startsWith(e)&&n.push(r)}}),n.sort()}function m(e,t){let n=t.guard(`storage.degraded`,`An emergency entry is not valid JSON. The library dropped it.`,()=>JSON.parse(e));return n===void 0?null:c.i(n)?n:(t.report(`storage.degraded`,`An emergency entry is not a batch. The library dropped it.`),null)}async function h(n,r){let i=0;for(let a of p(e.U,r)){let o=r.guard(`storage.unavailable`,`The library could not read the emergency queue.`,()=>{let e=localStorage.getItem(a);return localStorage.removeItem(a),e});if(!o)continue;let s=m(o,r);if(s!==null)try{await t.c(n.save(s),e.dn),i++}catch(e){r.report(`storage.degraded`,`The library could not recover an emergency batch.`,{key:a},e)}}return i}function g(t,n,r){let i=`writing the emergency queue, ${String(t.records.length)} records`,a=[],o=n.guard(`storage.quota_exceeded`,i,()=>{let r=p(e.U,n);for(let e of r.slice(0,Math.max(0,r.length-20+1))){let t=m(String(localStorage.getItem(e)),n);t!==null&&a.push(t),localStorage.removeItem(e)}return localStorage.setItem(f(e.U,t),JSON.stringify(t)),!0});n.guard(`pipeline.crashed`,`The loss report of the emergency queue failed.`,()=>{if(a.length>0){let e=a.flatMap(e=>e.records);r?.(`exit_queue_full`,e,a.map(e=>e.id))}o!==!0&&r?.(`quota`,t.records,[t.id])})}async function _(e,t){return await d(`ui-observability.emergency`,t,()=>h(e,t),{skipIfBusy:!1})??0}function v(e){return Array.isArray(e.records)&&e.records.some(c.r)}var y=class{howMany;isAudit;plain=[];audit=[];constructor(e,t){this.howMany=e,this.isAudit=t}add(e){return this.isAudit(e)?this.audit.length<this.howMany&&this.audit.push(e):this.plain.push(e),this.plain.length<this.howMany}picked(){return[...this.plain,...this.audit].slice(0,this.howMany)}};function b(e,t,n){let r=new y(t,n);for(let t of e)if(!r.add(t))break;return r.picked()}function x(e,t,n,r){return e.batches+=n,e.records+=r,e.reason=t,{batches:n,records:r,reason:t}}function S(e,t,n,r){n.batches!==0&&(e.report(`storage.evicted`,`The library dropped ${String(n.batches)} stored batches (${String(n.records)} records).`,{...n}),t?.(n,r))}function C(t){let n=e.x.length,r=Number(t.slice(n,n+14));return Number.isFinite(r)?r:null}var ee=class{limits;diagnostics;onGap;name=e.mn;constructor(e,t,n){this.limits=e,this.diagnostics=t,this.onGap=n}async save(e){if(this.write(e,`localStorage refused a batch, evicting the oldest`))await this.prune();else if(this.evictForQuota(),!this.write(e,`localStorage refused a batch even after evicting`)){let t={batches:1,records:e.records.length,reason:`quota`};S(this.diagnostics,this.onGap,t,[e])}}take(e){let t=[];for(let n of this.keys().slice(0,e)){let e=this.read(n);e===null?this.removeKey(n):t.push(e)}return Promise.resolve(t)}remove(e){let t=this.keyOf(e);return t!==null&&this.removeKey(t),Promise.resolve()}bumpAttempts(e,t){let n=this.keyOf(e);if(n===null)return Promise.resolve();let r=this.read(n);return r===null||(r.attempts=t,this.diagnostics.guard(`storage.degraded`,`The library could not update the attempt count.`,()=>{localStorage.setItem(n,JSON.stringify(r))})),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=[],r=[];for(let t of this.keys()){let i=C(t);i===null||i<e?n.push(t):r.push(t)}this.drop(t,`expired`,[...this.entries(n)]);let i=r.length-this.limits.maxBatches;return i>0&&this.drop(t,`over_capacity`,this.evictable(r,i)),Promise.resolve(t)}count(){return Promise.resolve(this.keys().length)}clear(){return this.evict(this.keys()),Promise.resolve()}close(){return Promise.resolve()}write(t,n){return this.diagnostics.guard(`storage.quota_exceeded`,n,()=>(localStorage.setItem(f(e.x,t),JSON.stringify(t)),!0))===!0}evictForQuota(){let e=this.keys(),t={batches:0,records:0,reason:`quota`},n=Math.ceil(e.length/4);this.drop(t,`quota`,this.evictable(e,n))}evictable(e,t){return b(this.entries(e),t,e=>e.batch!==null&&v(e.batch))}*entries(e){for(let t of e)yield{key:t,batch:this.read(t)}}drop(e,t,n){if(n.length===0)return;let r=[];for(let{key:e,batch:t}of n)this.removeKey(e),t&&r.push(t);let i=x(e,t,n.length,c.n(r));S(this.diagnostics,this.onGap,i,r)}read(e){let t=this.diagnostics.guard(`storage.unavailable`,`The library could not read a stored batch.`,()=>localStorage.getItem(e));if(!t)return null;let n=this.diagnostics.guard(`storage.degraded`,`A stored batch is corrupt. The library removed it.`,()=>JSON.parse(t));return n===void 0?null:c.i(n)?n:(this.diagnostics.report(`storage.degraded`,`A stored entry is not a batch. The library dropped it.`),null)}keyOf(e){return this.keys().find(t=>t.endsWith(`.${e}`))??null}evict(e){for(let t of e)this.removeKey(t)}removeKey(e){this.diagnostics.guard(`storage.degraded`,`The library could not remove a stored batch.`,()=>{localStorage.removeItem(e)})}keys(){return p(e.x,this.diagnostics)}},w=class{limits;onGap;name=e.hn;batches=[];constructor(e,t){this.limits=e,this.onGap=t}async save(e){this.batches.push(e),await this.prune()}take(e){return Promise.resolve(this.batches.slice(0,e))}remove(e){return this.batches=this.batches.filter(t=>t.id!==e),Promise.resolve()}bumpAttempts(e,t){let n=this.batches.find(t=>t.id===e);return n&&(n.attempts=t),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=this.batches.filter(t=>t.createdAt<e);this.batches=this.batches.filter(t=>t.createdAt>=e),this.report(t,`expired`,n);let r=this.batches.length-this.limits.maxBatches;if(r>0){let e=b(this.batches,r,v);this.batches=this.batches.filter(t=>!e.includes(t)),this.report(t,`over_capacity`,e)}return Promise.resolve(t)}report(e,t,n){if(n.length===0)return;let r=x(e,t,n.length,c.n(n));this.onGap?.(r,n)}count(){return Promise.resolve(this.batches.length)}clear(){return this.batches=[],Promise.resolve()}close(){return this.batches=[],Promise.resolve()}},te=t=>({name:e.gn,save:e=>(t?.({batches:1,records:e.records.length,reason:`not_stored`},[e]),Promise.resolve()),take:()=>Promise.resolve([]),remove:()=>Promise.resolve(),bumpAttempts:()=>Promise.resolve(),prune:()=>Promise.resolve({batches:0,records:0,reason:`expired`}),count:()=>Promise.resolve(0),clear:()=>Promise.resolve(),close:()=>Promise.resolve()});function ne(e){return e.guard(`storage.unavailable`,`The library could not read indexedDB.`,()=>globalThis.indexedDB!=null)===!0}function re(t){return t.guard(`storage.unavailable`,`The library could not write a test key to localStorage.`,()=>(localStorage.setItem(e._n,`1`),localStorage.removeItem(e._n),!0))===!0}async function ie(e,t,n,r,i){if(e===`none`)return te(i);if(e===`memory`)return new w(n,i);if(e===`indexeddb`||e===`auto`){if(ne(r)){let e=await r.guardAsync(`storage.unavailable`,`The library could not open IndexedDB.`,async()=>{let{IndexedDbStorage:e}=await Promise.resolve().then(()=>require("./indexeddb-storage-Cvavrf-y.cjs")),a=new e(t,n,r,i);return await a.open(),a});if(e)return e}if(e===`indexeddb`)return r.report(`storage.degraded`,`IndexedDB is not available. The library uses memory storage instead.`),new w(n,i)}return re(r)?new ee(n,r,i):(r.report(`storage.degraded`,`No persistent storage is available. The library keeps undelivered records in memory only.`),new w(n,i))}var T=class extends Error{kind;status;retryAfterMs;maxBytes;constructor(e,t,n,r,i,a){super(t,a===void 0?void 0:{cause:a}),this.kind=e,this.status=n,this.retryAfterMs=r,this.maxBytes=i,this.name=`TransportError`}};function ae(t){if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*e.wt);let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var E={"error.type":`type`,"error.message":`message`,"error.stack_trace":`stack_trace`},D=new Set([e.n,...Object.keys(E)]);function oe(t){return e.Et.test(t)?Number(BigInt(t)/e.Dt):Date.now()}function se(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:typeof e==`bigint`?e.toString():null}function ce(e,t,n){let r=e[t];r===void 0?e[t]=n:Array.isArray(r)?r.push(n):e[t]=[r,n]}function O(e,t,n,r){let i=se(n);if(i!==null)ce(e,t,i);else if(typeof n==`object`&&n&&!r.has(n)){if(r.add(n),Array.isArray(n))for(let i of n)O(e,t,i,r);else for(let[i,a]of Object.entries(n))O(e,`${t}.${i}`,a,r);r.delete(n)}}function k(e){let t=Object.create(null),n=new WeakSet;for(let[r,i]of Object.entries(e))O(t,r,i,n);return t}function le(e){let t=[];for(let[n,r]of Object.entries(E)){let i=e[n];typeof i==`string`&&t.push([r,i])}return t.length>0?Object.fromEntries(t):void 0}function ue(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>!(D.has(e)&&typeof t==`string`)))}var de={name:`ecs`,serialize(t){return{body:`${t.map(t=>{let n=oe(t.timeUnixNano),{attributes:r}=t,i=r[e.n];return JSON.stringify({"@timestamp":new Date(n).toISOString(),message:t.body,ecs:{version:e.V},log:{level:e.B[t.severityText]??t.severityText.toLowerCase(),logger:typeof i==`string`?i:void 0},event:{kind:r[`log.type`]===`metric`?`metric`:`event`},error:le(r),trace:{id:t.traceId},span:{id:t.spanId},service:{name:t.resource[e.Gt],version:t.resource[e.Kt],environment:t.resource[e.Vt]},user_agent:{original:t.resource[e.zt]},url:{full:r[`url.full`]??r[`page.url`]},labels:{...k(t.resource),...k(ue(r))}})}).join(`
2
- `)}\n`,contentType:e.N}}};function A(e){return e==null?null:typeof e==`string`?{stringValue:e}:typeof e==`boolean`?{boolValue:e}:typeof e==`number`?Number.isSafeInteger(e)?{intValue:String(e)}:{doubleValue:e}:typeof e==`bigint`?{intValue:e.toString()}:Array.isArray(e)?{arrayValue:{values:e.map(A).filter(e=>e!==null)}}:typeof e==`object`?{kvlistValue:{values:j(e)}}:null}function j(e){let t=[];for(let[n,r]of Object.entries(e)){let e=A(r);e&&t.push({key:n,value:e})}return t}var M=new WeakMap;function fe(e){let t=M.get(e);if(t!==void 0)return t;let n=JSON.stringify(e);return M.set(e,n),n}function N(e){let t=new Map;for(let n of e){let e=fe(n.resource),r=t.get(e);r?r.records.push(n):t.set(e,{resource:n.resource,records:[n]})}return[...t.values()]}var P={name:e.in,serialize(t){let n=N(t).map(t=>({resource:{attributes:j(t.resource)},scopeLogs:[{scope:{name:e.bn,version:e.xn},logRecords:t.records.map(e=>({timeUnixNano:e.timeUnixNano,observedTimeUnixNano:e.observedTimeUnixNano??e.timeUnixNano,severityNumber:e.severityNumber,severityText:e.severityText,body:{stringValue:e.body},traceId:e.traceId,spanId:e.spanId,flags:e.traceFlags,attributes:j(e.attributes)}))}]}));return{body:JSON.stringify({resourceLogs:n}),contentType:e.M}}},F=1;function I(e,t){let n=e.attributes[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function L(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isFinite(e))}function R(t){let n=t.attributes[e.St.attributeKeys],r={};if(!Array.isArray(n))return r;for(let e of n){let n=typeof e==`string`&&!e.startsWith(`metric.`)?t.attributes[e]:void 0;(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)&&(r[e]=n)}return r}function z(t){let n=I(t,e.St.count);if(n===void 0){let e=I(t,`metric.value`);return e===void 0?null:{count:`1`,sum:e<0?void 0:e,min:e,max:e,bucketCounts:[`1`],explicitBounds:[]}}let r=t.attributes[e.St.bounds],i=t.attributes[e.St.buckets];if(!L(r)||!L(i)||i.length!==r.length+1)return null;let a=I(t,e.St.min);return{count:String(n),sum:a!==void 0&&a<0?void 0:I(t,e.St.sum),min:a,max:I(t,e.St.max),bucketCounts:i.map(String),explicitBounds:r}}function B(e){let t=I(e,`metric.value`);return t===void 0?null:{asDouble:t}}function V(t,n){let r=t.attributes[e.St.start],i=n===`histogram`?z(t):B(t);return i===null?null:{attributes:j(R(t)),startTimeUnixNano:typeof r==`string`?r:t.timeUnixNano,timeUnixNano:t.timeUnixNano,...i}}function pe({name:e,unit:t,field:n,points:r}){if(n===`gauge`)return{name:e,unit:t,gauge:{dataPoints:r}};let i={aggregationTemporality:F,dataPoints:r};return n===`sum`&&(i.isMonotonic=r.every(e=>e.asDouble>=0)),{name:e,unit:t,[n]:i}}var me={name:e.in,serialize(t){let n=N(t).map(t=>{let n=new Map;for(let e of t.records){let t=e.attributes[`metric.type`],r=t===`counter`?`sum`:t===`histogram`?`histogram`:`gauge`,i=V(e,r);if(i===null)continue;let a=e.attributes[`metric.name`],o=e.attributes[`metric.unit`],s={name:typeof a==`string`?a:e.body,unit:typeof o==`string`?o:``,field:r,points:[]},c=JSON.stringify([s.field,s.name,s.unit]),l=n.get(c)??s;l.points.push(i),n.set(c,l)}return{resource:{attributes:j(t.resource)},scopeMetrics:[{scope:{name:e.bn,version:e.xn},metrics:[...n.values()].map(pe)}]}});return{body:JSON.stringify({resourceMetrics:n}),contentType:e.M}}},H={internal:1,client:3},he=2,ge=0,_e=new Set([e.d,...Object.values(e.ln)]);function U(e,t){let n=e.attributes[t];return typeof n==`string`?n:void 0}function ve(t){let n=Object.fromEntries(Object.entries(t.attributes).filter(([e])=>!_e.has(e))),r=U(t,e.ln.parentId);return{traceId:t.traceId,spanId:t.spanId,...r?{parentSpanId:r}:{},name:t.body,kind:U(t,e.ln.kind)===`client`?H.client:H.internal,startTimeUnixNano:U(t,e.ln.start)??t.timeUnixNano,endTimeUnixNano:U(t,e.ln.end)??t.timeUnixNano,attributes:j(n),status:{code:U(t,e.ln.status)===`error`?he:ge}}}var ye={name:e.in,serialize(t){let n=N(t).map(t=>({resource:{attributes:j(t.resource)},scopeSpans:[{scope:{name:e.bn,version:e.xn},spans:t.records.map(ve)}]}));return{body:JSON.stringify({resourceSpans:n}),contentType:e.M}}};function be(e){return e===`otlp`?P:e===`ecs`?de:e}function W(e,t){let n=t=>e.records.length>0&&e.records.every(e=>c.t(e,`log.type`)===t);return t.metricsEndpoint!==``&&n(`metric`)?`metrics`:n(`span`)?`traces`:`logs`}function G(e,t){return e===`metrics`?t.metricsEndpoint:e===`traces`?t.tracesEndpoint:t.endpoint}var xe={metrics:me,traces:ye};function K(e,t,n,r){try{return(xe[W(t,e)]??be(e.serializer)).serialize(t.records)}catch(e){n.report(`transport.serialize_failed`,r,{batchId:t.id},e);return}}var q=class{config;diagnostics;onSampling;onLoss;throttledUntil={logs:0,metrics:0,traces:0};acceptedAt=null;constructor(e,t,n=()=>void 0,r=()=>void 0){this.config=e,this.diagnostics=t,this.onSampling=n,this.onLoss=r}throttledForMs(e){return Math.max(0,this.throttledUntil[W(e,this.config)]-Date.now())}lastSendAt(){return this.acceptedAt}serialize(e){let t=K(this.config,e,this.diagnostics,`The serializer threw an error. The library dropped the batch.`);return t||this.onLoss(`unserializable`,e.records,[e.id]),t}accept(e,t){this.throttledUntil[e]=0,this.acceptedAt=Date.now(),this.config.sampling.remote&&t!=null&&this.onSampling(t)}reject(t,n,r,i){let a=String(t);if(t===401||t===403){let e=i.advice===void 0?``:` ${i.advice}`;return this.diagnostics.report(`transport.rejected_credentials`,`The server returned ${a}.${e}`,{status:t,endpoint:G(r,this.config)}),new T(`permanent`,`The server rejected the batch with ${a}.`,t)}if(t===413)return new T(`too_large`,`The payload is too large.`,t,void 0,i.maxBytes);if(t===429||t===503){let n=t===429,a=i.retryAfterMs===void 0?void 0:Math.min(i.retryAfterMs,e.en);return this.throttledUntil[r]=Date.now()+(a??2e3),n&&this.diagnostics.report(`transport.throttled`,`The server throttles the requests.`,{retryAfterMs:a}),new T(`throttled`,n?`The server throttles the requests.`:`The service is not available.`,t,a)}return t===408||t>=500?new T(`transient`,`The server returned the error ${a}.`,t):(this.diagnostics.report(`transport.dropped_permanent`,`The server rejected the batch with ${a}. The library dropped it.`,{batchId:n,status:t}),new T(`permanent`,`The server rejected the batch with ${a}.`,t))}};function J(e,t,n){return{kind:n,body:t.body,contentType:t.contentType,batchId:e.id,attempt:e.attempts,records:e.records}}function Se(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`status`);return typeof t==`number`&&Number.isInteger(t)&&t>=100&&t<=599}function Y(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):void 0}var Ce=class extends q{async send(n){let{transport:i}=this.config;if(!i||n.records.length===0)return;let o=this.serialize(n);if(!o)return;let s=W(n,this.config),c=J(n,o,s),l;try{l=await t.c(a.i(()=>a.r(()=>r.o(()=>i(c)))),e.Rt)}catch(e){let n=e instanceof t.s?e:void 0;throw new T(n?`timeout`:`transient`,n?.message??`The custom transport failed.`,void 0,void 0,void 0,e)}if(!Se(l))throw this.diagnostics.report(`transport.http_error`,`The custom transport returned no valid status. The library sends the batch again later.`,{batchId:n.id}),new T(`transient`,`The custom transport returned no valid status.`);let{status:u}=l;if(u>=200&&u<300)this.accept(s,l.sampling);else throw this.reject(u,n.id,s,{retryAfterMs:Y(l.retryAfterMs),maxBytes:Y(l.maxBytes)})}},we=class{deps;installed=!1;keepaliveBytes=0;onVisibility=()=>{document.visibilityState===`hidden`&&this.flush(`hidden`)};onPageHide=()=>{this.flush(`pagehide`)};onFreeze=()=>{this.flush(`freeze`)};onOpenFinClose=()=>{this.flush(`openfin-close`)};constructor(e){this.deps=e}install(){if(this.installed||typeof addEventListener>`u`)return;this.installed=!0,typeof document<`u`&&(document.addEventListener(`visibilitychange`,this.onVisibility),document.addEventListener(`freeze`,this.onFreeze)),addEventListener(`pagehide`,this.onPageHide);let e=o.t()?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`The library could not subscribe to close-requested.`,()=>{e?.on?.(`close-requested`,this.onOpenFinClose)})}uninstall(){if(!this.installed)return;this.installed=!1,typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),document.removeEventListener(`freeze`,this.onFreeze)),removeEventListener(`pagehide`,this.onPageHide);let e=o.t()?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`The library could not unsubscribe from close-requested.`,()=>{e?.removeListener?.(`close-requested`,this.onOpenFinClose)})}flush(e){let{config:t,diagnostics:n}=this.deps;if(n.guard(`pipeline.crashed`,`The metric points before the exit flush failed.`,()=>{this.deps.beforeExit?.()}),e===`hidden`){this.flushAlive();return}if(t.transport){this.flushCustom(e,t.transportOnExit);return}let r=this.endpointUrl();if(r!==null){this.keepaliveBytes=0;for(let i of this.deps.drainForExit()){let a=W(i,t),o=a===`logs`?r.href:G(a,t);o?this.flushBatch(i,e,new URL(o)):n.count(`record.dropped_no_destination`)}}}flushBatch(t,n,i){let{config:a}=this.deps;if(t.records.length===0)return;let o=this.serialize(t,n);if(!o)return;if(r.t(o.body)>6e4){this.park(t);return}i.searchParams.set(e.jt,t.id),i.searchParams.set(e.Mt,n);let s=i.toString(),c=this.deps.exitHeaders();if(c){this.keepaliveFetch(s,t,o.body,n,()=>{let n=new Headers(c);return n.set(e.$,o.contentType),n.set(e.Z,t.id),n});return}if(a.headers){this.park(t);return}let l=this.beacon(s,o.body);l!==`sent`&&(l===`refused`?this.park(t):this.keepaliveFetch(s,t,o.body,n,()=>new Headers({[e.$]:e.P})))}flushAlive(){let{diagnostics:e}=this.deps,t=`The flush of the hidden document failed.`;e.guard(`pipeline.crashed`,t,()=>{Promise.resolve(this.deps.flushAlive()).catch(n=>{e.report(`pipeline.crashed`,t,void 0,n)})})}flushCustom(e,t){let{config:n,diagnostics:r}=this.deps;for(let i of this.deps.drainForExit()){let o=this.serialize(i,e);if(!o)continue;let s=J(i,o,W(i,n));(t===void 0||r.guard(`transport.http_error`,`The transportOnExit hook threw an error.`,()=>a.r(()=>t(s)))!==!0)&&this.park(i)}}park(e){let{config:t,diagnostics:n,onLoss:r}=this.deps;t.storage===`memory`||t.storage===`none`?r?.(`not_stored`,e.records,[e.id]):g(e,n,r)}serialize(e,t){let n=K(this.deps.config,e,this.deps.diagnostics,`The ${t} exit flush could not serialize its batch.`);return n||this.deps.onLoss?.(`unserializable`,e.records,[e.id]),n}endpointUrl(){let{endpoint:e}=this.deps.config;return e?this.deps.diagnostics.guard(`config.invalid`,`The exit flush cannot use the endpoint ${e}.`,()=>new URL(e))??null:null}beacon(e,t){return this.deps.diagnostics.guard(`transport.http_error`,`The sendBeacon call failed.`,()=>{let n=globalThis.navigator;return n?.sendBeacon?n.sendBeacon(e,new Blob([t],{type:`text/plain;charset=UTF-8`}))?`sent`:`refused`:`unavailable`})??`unavailable`}keepaliveFetch(e,t,n,i,a){let{config:o,diagnostics:s}=this.deps,c=()=>{this.park(t)},l=r.t(n);this.keepaliveBytes+l>6e4?c():(this.keepaliveBytes+=l,s.guard(`transport.http_error`,`The keepalive fetch failed.`,()=>(fetch(e,{method:`POST`,body:n,headers:a(),credentials:o.credentials,keepalive:!0}).catch(e=>{s.report(`transport.http_error`,`The exit flush failed.`,{reason:i},e),c()}),!0))!==!0&&c())}};async function Te(t){let n=globalThis.CompressionStream;if(n===void 0)return null;let r=new Blob([t]).stream().pipeThrough(new n(e.W)),i=await new Response(r).arrayBuffer();return new Uint8Array(i)}var Ee=`In a cross-origin iframe, the session cookie is a third-party cookie. The browser often blocks it. Forward the records to the platform document. As an alternative, issue the cookie with the Partitioned attribute.`,X=class extends q{cachedHeaders;async send(e,t){let{config:n}=this,r=W(e,n),i=G(r,n);i?e.records.length!==0&&await this.post(e,r,i,t):this.diagnostics.count(`record.dropped_no_destination`)}lastHeaders(){let{headers:e}=this.config;if(!e)return;if(typeof e!=`function`)return e;let t=this.cachedHeaders;return t?.source===e&&t.endpoint===this.config.endpoint&&t.metricsEndpoint===this.config.metricsEndpoint&&t.tracesEndpoint===this.config.tracesEndpoint?t.headers:void 0}async post(t,n,r,i){let a=this.serialize(t);if(!a)return;let o=await this.attempt(t,r,a,i);if(this.rejectsCredentials(o.status)&&typeof this.config.headers==`function`&&(this.cachedHeaders=void 0,o=await this.attempt(t,r,a,i)),o.ok){this.accept(n,o.headers.get(e.tt));return}let s=o.status,c=ae(o.headers.get(e.et)),l=s===413?await this.readMaxBytes(o):void 0;throw this.reject(s,t.id,n,{retryAfterMs:c,maxBytes:l,advice:Ee})}rejectsCredentials(e){return e===401||e===403}async attempt(t,n,r,i){let a=Date.now()+e.Rt,o=new Headers(await this.before(this.resolveHeaders(),a,n));o.set(e.$,r.contentType),o.set(e.Z,t.id),o.set(e.X,String(t.attempts));let s=await this.before(this.encodeBody(r.body),a,n);typeof s!=`string`&&o.set(e.Q,e.W);let c=this.keepalive(s);return c&&i?.(),this.dispatch(n,o,s,a,c)}async before(e,n,r){try{return await t.c(e,Math.max(0,n-Date.now()))}catch{throw this.timeout(r)}}timeout(t){let n=`The request took longer than ${String(e.Rt)} ms.`;return this.diagnostics.report(`transport.timeout`,n,{endpoint:t}),new T(`timeout`,n)}async encodeBody(e){let{config:t}=this;return t.compression!==`gzip`||r.t(e)<1024?e:await this.diagnostics.guardAsync(`transport.http_error`,`The library could not compress the payload.`,()=>Te(e))??e}async dispatch(e,n,r,i,o){let{config:c}=this,l=new AbortController,u=setTimeout(()=>{l.abort()},Math.max(0,i-Date.now()));t.l(u);try{return await a.r(()=>fetch(e,{method:`POST`,headers:n,body:r,credentials:c.credentials,signal:l.signal,cache:`no-store`,keepalive:o}))}catch{throw l.signal.aborted?this.timeout(e):new T(s.r()?`transient`:`offline`,`A network error occurred.`)}finally{clearTimeout(u)}}keepalive(e){let t=globalThis.document?.visibilityState===`hidden`,n=typeof e==`string`?r.t(e):e.byteLength;return t&&n<=6e4}async readMaxBytes(e){return this.diagnostics.guardAsync(`transport.http_error`,`The library could not read the body of the 413 response.`,async()=>{let t=JSON.parse(await e.text());return typeof t.maxBytes==`number`?t.maxBytes:void 0})}async resolveHeaders(){let{headers:e}=this.config;if(!e)return{};if(typeof e!=`function`)return e;let{endpoint:t,metricsEndpoint:n,tracesEndpoint:r}=this.config,i=await this.diagnostics.guardAsync(`transport.http_error`,`The headers() function threw an error.`,()=>Promise.resolve(e()));return i&&(this.cachedHeaders={source:e,endpoint:t,metricsEndpoint:n,tracesEndpoint:r,headers:i}),i??{}}},De=class{storage;transport;diagnostics;config;batchesPerDrain;onLoss;timer=null;attempt=0;draining=!1;stopped=!1;maxAttempts;onOnline=()=>{this.attempt=0,this.schedule(0)};constructor(e,t,n,r,i=20,a=()=>void 0){this.storage=e,this.transport=t,this.diagnostics=n,this.config=r,this.batchesPerDrain=i,this.onLoss=a,this.maxAttempts=u(r.retention).maxAttempts}start(){this.stopped=!1,typeof addEventListener<`u`&&addEventListener(`online`,this.onOnline),this.schedule(e.$t)}nudge(){this.draining||this.schedule(e.Qt)}async storeFailed(e,t){let n=this.toStorable(e,t);for(let e of n)await this.bounded(this.storage.save(e));n.length>0&&this.nudge()}stop(){this.stopped=!0,typeof removeEventListener<`u`&&removeEventListener(`online`,this.onOnline),this.clearTimer()}schedule(e){if(this.stopped)return;this.clearTimer();let n=setTimeout(()=>{this.drain()},e);this.timer=n,t.l(n)}bounded(n){return t.c(n,e.dn)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}backoffMs(){let t=Math.min(e.Qt*2**this.attempt,e.en);return Math.random()*t}async drain(){if(!this.draining){this.draining=!0;try{await d(`ui-observability.drain`,this.diagnostics,()=>this.drainLocked())!==!0&&this.schedule(e.$t)}finally{this.draining=!1}}}async drainLocked(){try{if(!s.r())return this.schedule(e.$t),!0;let t=await this.bounded(this.storage.take(this.batchesPerDrain));if(t.length===0)return this.schedule(e.$t),!0;let n=new Set,r=0;for(let e of t){if(this.stopped)return!0;let t=W(e,this.config);if(n.has(t))continue;let i=await this.deliver(e);if(i===`stop`)return!0;i!==`next`&&(n.add(t),r=Math.max(r,i))}return n.size>0?this.schedule(r):this.schedule(t.length===this.batchesPerDrain?0:e.$t),!0}catch(e){return this.diagnostics.report(`storage.degraded`,`The drain loop threw an error.`,void 0,e),this.attempt++,this.schedule(this.backoffMs()),!0}}async deliver(t){if(t.attempts>=this.maxAttempts)return this.diagnostics.report(`storage.dead_lettered`,`The library dropped a batch after ${t.attempts.toString()} attempts.`,{batchId:t.id,records:t.records.length}),this.onLoss(`max_attempts`,t.records,[t.id]),await this.bounded(this.storage.remove(t.id)),`next`;try{return await this.transport.send(t),await this.bounded(this.storage.remove(t.id)),this.attempt=0,`next`}catch(n){let r=n instanceof T?n:void 0;return r?.kind===`permanent`||r?.kind===`too_large`?(await this.replaceStored(t,n),`next`):r?.kind===`offline`?(this.schedule(e.$t),`stop`):r?.kind===`throttled`?(this.attempt++,r.retryAfterMs??this.backoffMs()):(await this.bounded(this.storage.bumpAttempts(t.id,t.attempts+1)),this.attempt++,r?.retryAfterMs??this.backoffMs())}}async replaceStored(e,t){let n=this.toStorable(e,t);await this.bounded(this.storage.remove(e.id));for(let e of n)await this.bounded(this.storage.save(e))}toStorable(e,t){let n=t instanceof T?t:void 0;if(n?.kind===`permanent`)return this.onLoss(`rejected`,e.records,[e.id]),[];if(n?.kind!==`too_large`)return[e];let r=c.a(e,this.diagnostics);return r?(this.diagnostics.report(`transport.batch_split`,`The server refused the batch because it is too large.`,{from:e.records.length,to:r[0].records.length,serverMaxBytes:n.maxBytes}),r):(this.diagnostics.report(`transport.dropped_permanent`,`One record is larger than the server limit. The library dropped it.`,{batchId:e.id,bodies:e.records.map(e=>e.body)}),this.onLoss(`rejected`,e.records,[e.id]),[])}},Z=[`metrics`,`logs`,`traces`];function Q(t){let n=t.attributes[e.d];return n===`metric`?`metrics`:n===`span`?`traces`:`logs`}var $=class{options;onFlush;pending=[];timer=null;constructor(e,t){this.options=e,this.onFlush=t}add(e){this.pending.push(e),this.pending.length>=this.options.batchSize?this.onFlush(this):this.arm()}take(){this.clearTimer();let e=this.pending;return this.pending=[],e}get size(){return this.pending.length}stop(){this.clearTimer()}arm(){if(this.timer!==null)return;let e=setTimeout(()=>{this.timer=null,this.onFlush(this)},this.options.flushIntervalMs);this.timer=e,t.l(e)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},Oe=class{transport;storage;retry;diagnostics;streams;unconfirmed=new Map;queue=[];open=new Set;ceiling=new t.t;inFlight=0;pumpScheduled=!1;stopped=!1;constructor(e,t,n,r,i){this.transport=e,this.storage=t,this.retry=n,this.diagnostics=r;let a=e=>{this.claim(e)};this.streams={logs:new $(i.logs,a),metrics:new $(i.metrics,a),traces:new $(i.traces,a)}}push(e){this.stopped||(e.observedTimeUnixNano=n.r(),this.route(e))}drainForExit(){let e=[...this.unconfirmed.values()].flatMap(e=>e.records);return this.unconfirmed.clear(),Z.map(t=>this.toBatch([...e.filter(e=>Q(e)===t),...this.streams[t].take()])).filter(e=>e!==null)}async flushPending(){if(!this.stopped)for(let e of Z)this.claim(this.streams[e]);await Promise.all([...this.open].map(e=>e.done))}counts(){let e=e=>{let t=0;for(let n of e)t+=n.batch.records.length;return t},t=e(this.queue);return{pending:Z.reduce((e,t)=>e+this.streams[t].size,0)+t,inFlight:e(this.open)-t}}destroy(){this.stopped=!0;for(let e of Z)this.streams[e].stop();this.queue.length=0;for(let e of this.open)e.resolve();this.open.clear()}toBatch(e){return e.length===0?null:{id:i.i(this.diagnostics),records:e,createdAt:Date.now(),attempts:0}}route(e){try{let t=this.streams[Q(e)];if(!this.ceiling.allow(e)){this.diagnostics.count(`record.dropped_by_ceiling`);return}t.add(e)}catch(e){this.diagnostics.report(`pipeline.crashed`,`The pipeline dropped a record before it reached a stream.`,void 0,e)}}claim(e){this.enqueue(this.toBatch(e.take()))}enqueue(e){if(!e)return;let t,n={batch:e,done:new Promise(e=>{t=e}),resolve:t};this.unconfirmed.set(e.id,e),this.open.add(n),this.queue.push(n),!this.pumpScheduled&&(this.pumpScheduled=!0,queueMicrotask(()=>{this.pumpScheduled=!1,this.pump()}))}pump(){for(;this.inFlight<2;){let e=this.queue.shift();if(!e)return;this.inFlight++,this.run(e)}}async run(e){let{batch:t}=e;try{await this.dispatch(t)}catch(e){this.diagnostics.report(`pipeline.crashed`,`A dispatch rejected its promise. This must not occur.`,{batchId:t.id},e)}finally{this.inFlight--,this.open.delete(e),e.resolve(),this.pump()}}async dispatch(e){try{let t=this.transport.throttledForMs(e);if(t>0){await this.store(e),this.diagnostics.report(`transport.throttled`,`The server throttles requests. The pipeline stored the batch and did not send it.`,{batchId:e.id,records:e.records.length,throttledMs:t});return}try{await this.transport.send(e,()=>{this.unconfirmed.delete(e.id)})}catch(t){await this.storeFailed({...e,attempts:e.attempts+1},t),this.diagnostics.report(`transport.http_error`,`The send failed. The pipeline stored the batch for a retry.`,{batchId:e.id,records:e.records.length},t)}}finally{this.unconfirmed.delete(e.id)}}async storeFailed(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store an undelivered batch.`,async()=>{await this.retry.storeFailed(e,t)})}async store(n){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not store an undelivered batch.`,async()=>{await t.c(this.storage.save(n),e.dn),this.retry.nudge()})}},ke=class t{storage;retry;pipeline;exitFlush;diagnostics;transport;constructor(e,t,n,r,i,a){this.storage=e,this.retry=t,this.pipeline=n,this.exitFlush=r,this.diagnostics=i,this.transport=a}static async create(n){let{config:r,diagnostics:i}=n,a=await ie(r.storage,e.un,u(r.retention),i,n.onGap),o=e=>{let t=l.n(e,i);t&&l.t(n.remote,r,t)},{onLoss:s}=n,c=r.transport?void 0:new X(r,i,o,s),d=c??new Ce(r,i,o,s),f=new De(a,d,i,r,20,s),{batching:p}=r,m=new Oe(d,a,f,i,{logs:{flushIntervalMs:p.logFlushIntervalMs,batchSize:p.logBatchSize},metrics:{flushIntervalMs:p.metricFlushIntervalMs,batchSize:p.metricBatchSize},traces:{flushIntervalMs:p.logFlushIntervalMs,batchSize:p.logBatchSize}}),h=new we({config:r,diagnostics:i,drainForExit:()=>m.drainForExit(),flushAlive:()=>m.flushPending(),exitHeaders:()=>c?.lastHeaders(),onLoss:s,beforeExit:n.beforeExit}),g=!1;try{h.install(),f.start(),g=!0}finally{g||(h.uninstall(),f.stop())}let _=new t(a,f,m,h,i,d);return _.importEmergency(),_}push(e){this.pipeline.push(e)}async flush(){await this.pipeline.flushPending()}async queueDepth(){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not count the batches in storage.`,()=>this.storage.count())??0}stats(){return{...this.pipeline.counts(),lastSendAt:this.transport.lastSendAt()}}async destroy(){await this.diagnostics.guardAsync(`pipeline.crashed`,`The flush before shutdown failed.`,()=>this.flush()),this.exitFlush.flush(`shutdown`),this.exitFlush.uninstall(),this.retry.stop(),this.pipeline.destroy(),await this.storage.close()}async importEmergency(){let e=await this.diagnostics.guardAsync(`storage.degraded`,`The emergency import failed.`,()=>_(this.storage,this.diagnostics));e!==void 0&&e>0&&this.retry.nudge()}};exports.Sender=ke,exports.i=v,exports.n=S,exports.r=y,exports.t=x;
3
- //# sourceMappingURL=sender-6vrT9fFL.cjs.map