@himetrica/replaykit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may accept and charge a
167
+ fee for acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed" page as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Himetrica
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,92 @@
1
- # Temporary Holding Version
1
+ # @himetrica/replaykit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Session replay and friction signals for the web, by [Himetrica](https://himetrica.com).
4
+
5
+ ReplayKit records what happened on the page in the sessions that matter (an error, a rage click, a checkout, a paying customer) and flags friction in every session: rage clicks, dead clicks, JavaScript errors, back navigation and abandoned forms. Every recording belongs to the visitor and session the Himetrica tracker already knows, so you can go from a customer, a campaign or a revenue number straight to what they saw.
6
+
7
+ ReplayKit is a separate, optional SDK. It needs the Himetrica tracker on the same page.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @himetrica/replaykit
13
+ ```
14
+
15
+ ```ts
16
+ import * as ReplayKit from "@himetrica/replaykit";
17
+
18
+ ReplayKit.init({ apiKey: "hm_..." }); // the same public key the tracker uses
19
+ ```
20
+
21
+ Or with a script tag, after the tracker:
22
+
23
+ ```html
24
+ <script src="https://unpkg.com/@himetrica/replaykit/dist/replaykit.global.js" data-api-key="hm_..."></script>
25
+ ```
26
+
27
+ What gets recorded, and when, is configured per project in the dashboard (Settings → ReplayKit). The SDK reads it on every page, so changes apply without a deploy.
28
+
29
+ ## When a session is recorded
30
+
31
+ By default ReplayKit does not record everything. It keeps the last ~30 seconds of the page in memory and only uploads a recording when one of these happens:
32
+
33
+ | Trigger | When |
34
+ | --- | --- |
35
+ | Error | A JavaScript error or unhandled promise rejection |
36
+ | Rage click | 3 or more clicks on the same spot within a second |
37
+ | Checkout | The visitor reaches a checkout path (configurable globs, e.g. `/checkout*`) |
38
+ | Paying customer | The visitor is a paying customer (decided by Himetrica) |
39
+ | Sample | A share of all sessions (5% by default) |
40
+ | Manual | You call `ReplayKit.start()` or `ReplayKit.trigger()` |
41
+
42
+ Because the last seconds are kept, the recording shows what led up to the trigger, including the previous page of the same session.
43
+
44
+ Signals are sent for every session (they are tiny and do not count against your recordings quota), even when recordings are turned off for the project.
45
+
46
+ ## API
47
+
48
+ ```ts
49
+ ReplayKit.init({ apiKey, apiUrl?, allowLocalhost?, debug? });
50
+
51
+ ReplayKit.start(); // record this session from now on
52
+ ReplayKit.trigger("refund"); // this moment matters: record it (reason is only logged with debug)
53
+ ReplayKit.stop(); // stop recording for the rest of the session
54
+ ReplayKit.consent(true); // the visitor accepted your banner (see "Consent")
55
+ ReplayKit.getRecordingId(); // id of the recording running on this page, or null
56
+ ReplayKit.shutdown(); // remove every listener
57
+ ```
58
+
59
+ ## Privacy
60
+
61
+ These are on for every project and cannot be turned off:
62
+
63
+ - **Every input is masked.** Typed values are replaced by `*` before anything leaves the browser, passwords and card fields included.
64
+ - **Card fields and blocked elements never leave the page.** `input[type=password]`, `[autocomplete^="cc-"]`, `[data-hm-block]` and `.hm-block` are replaced by an empty box of the same size.
65
+ - **Query strings are never sent** with signals or page URLs.
66
+ - Canvas, cross-origin iframes and images inlined as data are not recorded.
67
+
68
+ You can go further:
69
+
70
+ - Mark any text with `class="hm-mask"` or `data-hm-mask` to mask it.
71
+ - Turn on "Mask all text" in the project to mask every text node.
72
+ - Add your own selectors to block, and paths never to record.
73
+
74
+ ### Consent
75
+
76
+ With "Require consent" on in the project, nothing is recorded until your consent banner calls:
77
+
78
+ ```ts
79
+ ReplayKit.consent(true); // or false to stop and drop anything not uploaded yet
80
+ ```
81
+
82
+ The answer is remembered on the device. `consent(false)` stops recording even when the project does not require consent.
83
+
84
+ ## How it works
85
+
86
+ - Chunks of the recording are compressed in the browser (gzip) and uploaded straight to storage with a short-lived signed URL. They never pass through Himetrica's servers.
87
+ - Recordings are deleted after 30 days.
88
+ - rrweb is only downloaded on pages that may record; a page that only sends signals stays light.
89
+
90
+ ## License
91
+
92
+ Apache-2.0
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var q="hm_rk_state",p=class{constructor(t){this.env=t;this.cache=null}load(t){if(_optionalChain([this, 'access', _2 => _2.cache, 'optionalAccess', _3 => _3.sid])===t)return this.cache;let e=null;try{let r=this.env.getSession(q);r&&(e=JSON.parse(r))}catch (e2){e=null}return(!e||e.sid!==t||typeof e.seq!="number")&&(e={sid:t,seq:0}),this.cache=e,e}save(t){this.cache=t;try{this.env.setSession(q,JSON.stringify(t))}catch (e3){}}};function E(i,t){return{startedAt:i,endedAt:i,activeMs:0,clicks:0,rageClicks:0,deadClicks:0,errors:0,pages:1,entryUrl:t}}var L=typeof window<"u"&&typeof document<"u";function J(){let i=globalThis.crypto;if(i&&typeof i.randomUUID=="function")try{return i.randomUUID()}catch (e4){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function M(i,t){try{return i().getItem(t)}catch (e5){return null}}function F(i,t,e){try{e===null?i().removeItem(t):i().setItem(t,e)}catch (e6){}}function Q(){if(typeof indexedDB>"u")return;let i=null,t=()=>_nullishCoalesce(i, () => ((i=new Promise((r,s)=>{let n=indexedDB.open("himetrica-replaykit",1);n.onupgradeneeded=()=>n.result.createObjectStore("kv"),n.onsuccess=()=>r(n.result),n.onerror=()=>s(n.error)})))),e=(r,s)=>t().then(n=>new Promise(a=>{let o=n.transaction("kv",r),l=s(o.objectStore("kv"));o.oncomplete=()=>a(l?l.result:void 0),o.onerror=o.onabort=()=>a(void 0)})).catch(()=>{});return{get:r=>e("readonly",s=>s.get(r)),set:(r,s)=>e("readwrite",n=>{n.put(s,r)}).then(()=>{}),del:r=>e("readwrite",s=>{s.delete(r)}).then(()=>{})}}function Z(){if(!(typeof CompressionStream>"u"||typeof Blob>"u"||typeof Response>"u"))return i=>new Response(new Blob([i]).stream().pipeThrough(new CompressionStream("gzip"))).blob()}function B(){let i=typeof fetch=="function"?fetch.bind(globalThis):void 0,t=typeof navigator<"u"?navigator:void 0;return{now:()=>Date.now(),uuid:()=>J(),fetch:i,sendBeacon:t&&typeof t.sendBeacon=="function"?(e,r)=>{try{return t.sendBeacon(e,new Blob([r],{type:"text/plain"}))}catch (e7){return!1}}:void 0,getLocal:e=>M(()=>localStorage,e),setLocal:(e,r)=>F(()=>localStorage,e,r),getSession:e=>M(()=>sessionStorage,e),setSession:(e,r)=>F(()=>sessionStorage,e,r),getCookie:e=>{try{let r=document.cookie.match(new RegExp("(?:^|; )"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"=([^;]*)"));return r?decodeURIComponent(r[1]):null}catch (e8){return null}},store:Q(),gzip:Z(),setTimer:(e,r)=>setTimeout(e,r),clearTimer:e=>clearTimeout(e)}}function N(i){let t=i.getCookie("hm_vid")||i.getLocal("hm_visitor_id")||void 0,e=i.getCookie("hm_sid")||i.getSession("hm_session_id")||void 0;return{visitorId:t,sessionId:e}}function tt(i,t){let e=i.trim().toLowerCase();if(!e)return!1;let r=(t||"/").toLowerCase();if(!e.includes("*")){let n=e.endsWith("/")&&e.length>1?e.slice(0,-1):e;return r===n||r.startsWith(n.endsWith("/")?n:n+"/")}return new RegExp("^"+e.split("*").map(et).join(".*")+"$").test(r)}function x(i,t){for(let e of i)if(tt(e,t))return!0;return!1}function et(i){return i.replace(/[.+?^${}()|[\]\\]/g,"\\$&")}function it(i){let t=3735928559,e=1103547991;for(let s=0;s<i.length;s++){let n=i.charCodeAt(s);t=Math.imul(t^n,2654435761),e=Math.imul(e^n,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),(4294967296*(2097151&e)+(t>>>0))/9007199254740992}function O(i,t){return t>0?t>=1?!0:it(i)<t:!1}function u(i){let t=i.search(/[?#]/);return t===-1?i:i.slice(0,t)}var _="replaykit:page";function D(i,t,e){let r=[],s=t;for(let n of i){let a;if(n.type===4)a=_optionalChain([n, 'access', _4 => _4.data, 'optionalAccess', _5 => _5.href]);else if(n.type===5){let c=n.data;_optionalChain([c, 'optionalAccess', _6 => _6.tag])===_&&(a=_optionalChain([c, 'access', _7 => _7.payload, 'optionalAccess', _8 => _8.href]))}if(typeof a!="string"||!a)continue;let o=a.search(/[?#]/),l=(o===-1?a:a.slice(0,o)).slice(0,500);if(l!==s&&(s=l,r.push({url:l,ts:n.timestamp}),r.length>=e))break}return r}var w=3e4,f=3e4;function rt(i,t){return t>0&&i[t-1].type===4?t-1:t}function C(i,t,e=w){let r=t-e,s=-1,n=-1;for(let o=0;o<i.length;o++)if(i[o].type===2)if(n===-1&&(n=o),i[o].timestamp<=r)s=o;else break;if(s===-1&&(s=n),s===-1)return[];let a=rt(i,s);return a===0?i:i.slice(a)}function I(i){try{return JSON.stringify(i).length}catch (e9){return 0}}var g=class{constructor(){this.burst=null}onClick(t){let e=this.burst;if(e&&t.ts-e.lastTs<=1e3&&st(e.first,t))return e.count++,e.lastTs=t.ts,{trigger:e.count===3,finished:null};let r=e&&e.count>=3?e:null;return this.burst={first:t,count:1,lastTs:t.ts},{trigger:!1,finished:r}}flush(t){let e=this.burst;return!e||t-e.lastTs<=1e3?null:(this.burst=null,e.count>=3?e:null)}currentCount(){return _nullishCoalesce(_optionalChain([this, 'access', _9 => _9.burst, 'optionalAccess', _10 => _10.count]), () => (0))}};function st(i,t){return i.target&&i.target===t.target?!0:Math.abs(i.x-t.x)<=30&&Math.abs(i.y-t.y)<=30}var U=500;function H(i){return i.isFormField||i.hasSelection||i.tag==="html"||i.tag==="body"?!1:i.insideInteractive||i.pointerCursor}function W(i){return i.mutations===0&&!i.urlChanged&&!i.scrolled&&!i.focusChanged&&!i.unloading}var nt=5e3;function A(i,t){if(!i)return 0;let e=t-i;return e>0&&e<=nt?e:0}function G(i){return!i.record||!i.canGzip||i.state.stopped||i.excluded||i.consent===!1?{kind:"off"}:i.requireConsent&&i.consent!==!0?{kind:"wait_consent"}:i.state.rid?{kind:"continue"}:i.forceTrigger?{kind:"start",trigger:i.forceTrigger}:i.checkout?{kind:"start",trigger:"checkout"}:i.sampled?{kind:"start",trigger:"sample"}:{kind:"buffer"}}function ot(i){return i>=200&&i<300?"ok":i===401?"stop":i===403?"off":i===429?"quota":i===400||i===413||i===404||i===422?"drop":"retry"}var m=class{constructor(t,e,r){this.env=t;this.apiUrl=e;this.apiKey=r}url(t){return`${this.apiUrl}/api/t/r/${t}?apiKey=${encodeURIComponent(this.apiKey)}`}init(t){return this.post("init",t,!0)}chunk(t){return this.post("chunk",t,!0)}signals(t){return this.post("signals",t,!1)}beaconSignals(t){return!!_optionalChain([this, 'access', _11 => _11.env, 'access', _12 => _12.sendBeacon, 'optionalCall', _13 => _13(this.url("signals"),JSON.stringify(t))])}async put(t,e){if(!this.env.fetch)return"retry";try{let r=await this.env.fetch(t,{method:"PUT",body:e,headers:{"Content-Type":"application/gzip"}});return r.status>=200&&r.status<300?"ok":r.status===400||r.status===413?"drop":"retry"}catch (e10){return"retry"}}async post(t,e,r){if(!this.env.fetch)return{outcome:"retry"};try{let s=await this.env.fetch(this.url(t),{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"text/plain"},keepalive:!1,credentials:"omit"}),n=ot(s.status);if(n!=="ok"||!r)return{outcome:n};try{return{outcome:n,data:await s.json()}}catch (e11){return{outcome:"retry"}}}catch (e12){return{outcome:"retry"}}}},at=2e3,lt=6e4;function d(i){return Math.min(lt,at*2**Math.max(0,i-1))}var ut=5e3,ht=200,ct=500,dt=2e3,v=class{constructor(t,e,r){this.env=t;this.api=e;this.ids=r;this.queue=[];this.timer=null;this.sentThisPage=0;this.failures=0;this.busy=!1;this.last=new Map;this.disabled=!1;this.held=!0}add(t){if(this.disabled||this.sentThisPage+this.queue.length>=ht)return;let e=`${t.type}|${t.url}|${t.selector||""}|${t.detail||""}`,r=this.last.get(e);r!==void 0&&t.ts-r<dt||(this.last.set(e,t.ts),this.queue.push(t),this.queue.length>ct&&this.queue.shift(),!this.held&&(this.queue.length>=50?this.schedule(0):this.timer||this.schedule(ut)))}release(t){if(this.held=!1,!t){this.disable();return}this.queue.length&&this.schedule(0)}disable(){this.disabled=!0,this.queue=[],this.timer&&this.env.clearTimer(this.timer),this.timer=null}schedule(t){this.timer&&this.env.clearTimer(this.timer),this.timer=this.env.setTimer(()=>{this.timer=null,this.flush()},t)}async flush(){if(!(this.busy||this.held||this.disabled)){this.busy=!0;try{for(;this.queue.length&&!this.disabled;){let t=this.queue.slice(0,50),e=await this.api.signals({...this.ids(),signals:t});if(e.outcome==="ok"||e.outcome==="drop"||e.outcome==="quota"){this.queue.splice(0,t.length),this.sentThisPage+=t.length,this.failures=0;continue}if(e.outcome==="off"||e.outcome==="stop"){this.disable();return}this.failures++,this.schedule(d(this.failures));return}}finally{this.busy=!1}}}beacon(){if(!(this.held||this.disabled||!this.queue.length))for(;this.queue.length;){let t=this.queue.slice(0,50);if(!this.api.beaconSignals({...this.ids(),signals:t}))return;this.queue.splice(0,t.length),this.sentThisPage+=t.length}}get size(){return this.queue.length}};var V='a[href],button,summary,[role="button"],[role="link"],[role="tab"],[role="menuitem"],[role="checkbox"],[role="switch"],[role="option"],[onclick]',Y="input,textarea,select,label,option,[contenteditable],[contenteditable=true]",ft=".hm-mask,[data-hm-mask],[data-hm-block],.hm-block",z=80,gt=200;function y(i){let t=[],e=i;for(let r=0;e&&r<3&&e.nodeType===1;r++){let s=e.tagName.toLowerCase();if(s==="html"||s==="body")break;if(e.id&&/^[A-Za-z][\w-]{0,40}$/.test(e.id)&&!/\d{3,}/.test(e.id)){t.unshift(`${s}#${e.id}`);break}let n=(typeof e.className=="string"?e.className:"").split(/\s+/).filter(a=>a&&a.length<30&&!/\d{3,}|^css-|^sc-|__/.test(a)).slice(0,2);t.unshift(s+n.map(a=>"."+a).join("")),e=e.parentElement}return t.join(" > ")}function X(i,t){if(t||i.closest(ft)||i.closest(Y))return;let e=(_nullishCoalesce(_nullishCoalesce(i.innerText, () => (i.textContent)), () => (""))).replace(/\s+/g," ").trim();return e?e.slice(0,z):_optionalChain([(i.getAttribute("aria-label")||i.getAttribute("title")||void 0), 'optionalAccess', _14 => _14.slice, 'call', _15 => _15(0,z)])}function mt(i){let t=!1;try{t=getComputedStyle(i).cursor==="pointer"}catch (e13){t=!1}let e=typeof getSelection=="function"?getSelection():null;return{tag:i.tagName.toLowerCase(),insideInteractive:!!i.closest(V),isFormField:!!i.closest(Y),pointerCursor:t,hasSelection:!!e&&!e.isCollapsed&&e.toString().trim().length>0}}function vt(i){let t=i instanceof Element?i:i instanceof Node?i.parentElement:null;return t?t.closest(V)||t:null}var b=class{constructor(t){this.h=t;this.rage=new g;this.rageEl=null;this.rageTimer=null;this.lastHref="";this.hrefTimer=null;this.unloading=!1;this.lastScrollInput=0;this.forms=new Map;this.errorsSeen=new Set;this.off=[]}start(){this.lastHref=location.href;let t=(e,r,s=window)=>{let n={capture:!0,passive:!0};s.addEventListener(e,r,n),this.off.push(()=>s.removeEventListener(e,r,n))};t("click",e=>this.onClick(e)),t("keydown",()=>this.h.input("key",this.h.now())),t("scroll",()=>{let e=this.h.now();e-this.lastScrollInput>250&&(this.lastScrollInput=e,this.h.input("scroll",e))}),t("error",e=>this.onError(e.message||_optionalChain([e, 'access', _16 => _16.error, 'optionalAccess', _17 => _17.message])||"")),t("unhandledrejection",e=>{let r=e.reason;this.onError(typeof r=="string"?r:_optionalChain([r, 'optionalAccess', _18 => _18.message])||"Unhandled promise rejection")}),t("popstate",()=>this.backNav()),t("input",e=>this.onField(e.target)),t("change",e=>this.onField(e.target)),t("submit",e=>{e.target instanceof HTMLFormElement&&this.forms.delete(e.target)}),t("pageshow",()=>{this.unloading=!1}),this.hrefTimer=setInterval(()=>this.checkHref(),1e3);try{_optionalChain([performance, 'access', _19 => _19.getEntriesByType, 'call', _20 => _20("navigation"), 'access', _21 => _21[0], 'optionalAccess', _22 => _22.type])==="back_forward"&&this.emit({type:"back_nav",detail:u(location.href)})}catch (e14){}}stop(){for(let t of this.off)t();this.off=[],this.hrefTimer&&clearInterval(this.hrefTimer),this.rageTimer&&clearTimeout(this.rageTimer),this.hrefTimer=this.rageTimer=null}pageHide(){this.unloading=!0,this.flushForms(),this.flushRage(!0)}emit(t){this.h.signal({ts:_nullishCoalesce(t.ts, () => (this.h.now())),url:u(location.href),...t})}checkHref(){let t=location.href;if(t===this.lastHref)return;let e=this.lastHref;this.lastHref=t,u(t)!==u(e)&&this.h.navigated(u(t))}onClick(t){let e=this.h.now();this.h.input("click",e);let r=vt(t.target);if(!r)return;let s=y(r),n=this.rage.onClick({x:t.clientX,y:t.clientY,ts:e,target:s});n.finished&&this.reportRage(n.finished.count,n.finished.first.ts),n.trigger&&this.h.trigger("rage_click"),this.rageEl=this.rage.currentCount()===1?r:this.rageEl,this.rageTimer&&clearTimeout(this.rageTimer),this.rageTimer=setTimeout(()=>this.flushRage(!1),1050),this.rage.currentCount()===1&&this.watchDeadClick(r,s,e)}flushRage(t){let e=this.rage.flush(t?Number.MAX_SAFE_INTEGER:this.h.now());e&&this.reportRage(e.count,e.first.ts)}reportRage(t,e){let r=this.rageEl;this.emit({type:"rage_click",ts:e,count:t,selector:r?y(r):void 0,text:r?X(r,this.h.maskAllText()):void 0})}watchDeadClick(t,e,r){if(!H(mt(t)))return;let s=location.href,n=`${scrollX},${scrollY}`,a=document.activeElement,o=0,l=null;try{l=new MutationObserver(c=>{o+=c.length}),l.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0})}catch (e15){return}setTimeout(()=>{if(_optionalChain([l, 'optionalAccess', _23 => _23.disconnect, 'call', _24 => _24()]),this.rage.currentCount()>1)return;W({mutations:o,urlChanged:location.href!==s,scrolled:`${scrollX},${scrollY}`!==n,focusChanged:document.activeElement!==a&&document.activeElement!==t,unloading:this.unloading})&&this.emit({type:"dead_click",ts:r,selector:e,text:X(t,this.h.maskAllText())})},U)}onError(t){let e=(t||"Error").slice(0,gt);this.errorsSeen.has(e)||(this.errorsSeen.add(e),this.emit({type:"error",detail:e}),this.h.trigger("error"))}backNav(){this.emit({type:"back_nav",detail:u(location.href)}),this.checkHref()}onField(t){if(!(t instanceof Element))return;let e=t.closest("form");if(!e)return;let r=t.getAttribute("name")||t.id||y(t),s=this.forms.get(e);s||this.forms.set(e,s=new Set),s.add(r)}flushForms(){for(let[t,e]of this.forms)!t.isConnected&&e.size===0||this.emit({type:"form_abandon",selector:y(t),count:e.size});this.forms.clear()}};var yt=["[data-hm-block]",".hm-block",'[autocomplete^="cc-"]','input[type="password"]'],bt=".hm-mask,[data-hm-mask]",kt=null;function St(){return _nullishCoalesce(kt, () => ((kt=Promise.resolve().then(() => _interopRequireWildcard(require("@rrweb/record"))).then(i=>i.record))))}function Rt(i){return i.filter(t=>{if(!t||typeof t!="string")return!1;try{return document.createDocumentFragment().querySelector(t),!0}catch (e16){return!1}})}var k=class{constructor(){this.record=null;this.stopped=!1}async start(t){try{this.record=await St()}catch (e17){return!1}if(this.stopped)return!1;try{return this.stopFn=_nullishCoalesce(this.record({emit:e=>t.emit(e),checkoutEveryNms:f,maskAllInputs:!0,maskInputOptions:{password:!0},maskTextSelector:t.maskAllText?"*":bt,blockSelector:Rt([...yt,...t.blockSelectors]).join(","),recordCanvas:!1,recordCrossOriginIframes:!1,inlineImages:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:!0},sampling:{mousemove:50,scroll:150,input:"last"}}), () => (void 0)),!!this.stopFn}catch (e18){return!1}}snapshot(){try{_optionalChain([this, 'access', _25 => _25.record, 'optionalAccess', _26 => _26.takeFullSnapshot, 'call', _27 => _27(!0)])}catch (e19){}}page(t){try{_optionalChain([this, 'access', _28 => _28.record, 'optionalAccess', _29 => _29.addCustomEvent, 'call', _30 => _30(_,{href:t})])}catch (e20){}}stop(){this.stopped=!0;try{_optionalChain([this, 'access', _31 => _31.stopFn, 'optionalCall', _32 => _32()])}catch (e21){}this.stopFn=void 0}};var Tt=3e4,Et=256*1024,S=i=>`rk:pending:${i}`,R=class{constructor(t,e,r,s,n){this.env=t;this.api=e;this.states=r;this.ids=s;this.hooks=n;this.queue=[];this.inflight=[];this.queuedBytes=0;this.timer=null;this.retryTimer=null;this.failures=0;this.busy=!1;this.stopped=!1;this.epoch=0;this.parked=!1;this.lastPage="";this.lastPageRid=""}state(){return this.states.load(this.ids.sid)}async restorePending(){let t=this.env.store;if(!t)return;let e=await t.get(S(this.ids.sid));if(!e)return;await t.del(S(this.ids.sid));let r=this.state();!r.rid||e.rid!==r.rid||!Array.isArray(e.events)||e.events.length===0||(this.queue=e.events.concat(this.queue),this.queuedBytes+=e.events.reduce((s,n)=>s+I(n),0),this.schedule(0))}add(t){this.stopped||(this.queue.push(t),this.queuedBytes+=I(t),this.queuedBytes>=Et?this.schedule(0):this.timer||this.schedule(Tt))}addMany(t){for(let e of t)this.add(e)}schedule(t){this.timer&&this.env.clearTimer(this.timer),this.timer=this.env.setTimer(()=>{this.timer=null,this.flush()},t)}async flush(){if(this.busy||this.stopped)return;let t=this.epoch;this.busy=!0;try{for(;!this.stopped&&t===this.epoch&&(this.inflight.length>0||this.queue.length>0);)if(this.inflight.length===0&&(this.inflight=this.queue,this.queue=[],this.queuedBytes=0),!await this.sendInflight())return}finally{this.busy=!1}}async sendInflight(){_optionalChain([this, 'access', _33 => _33.hooks, 'access', _34 => _34.beforeChunk, 'optionalCall', _35 => _35()]);let t=this.state();if(!t.rid||!t.trigger||!t.stats)return!1;if(t.seq>=600)return this.stop("limit"),!1;let e=this.env.gzip;if(!e)return this.stop("off"),!1;let r={v:1,rid:t.rid,seq:t.seq,events:this.inflight},s=await e(JSON.stringify(r));if(s.size>2097152){if(this.inflight.length>1){let P=Math.ceil(this.inflight.length/2);return this.queue=this.inflight.slice(P).concat(this.queue),this.inflight=this.inflight.slice(0,P),!0}return this.stop("limit"),!1}let n=this.lastPageRid===t.rid?this.lastPage:"",a=D(this.inflight,n,50),o=await this.api.chunk({rid:t.rid,sid:this.ids.sid,vid:this.ids.vid,seq:t.seq,bytes:s.size,trigger:t.trigger,stats:t.stats,pages:a});if(o.outcome==="drop")return this.inflight=[],!0;if(o.outcome==="quota")return this.stop("quota"),!1;if(o.outcome==="off"||o.outcome==="stop")return this.stop("off"),!1;if(o.outcome!=="ok"||!_optionalChain([o, 'access', _36 => _36.data, 'optionalAccess', _37 => _37.url]))return this.retryLater(),!1;let l=await this.api.put(o.data.url,s);if(l==="drop")return this.inflight=[],!0;if(l!=="ok")return this.retryLater(),!1;this.failures=0,this.inflight=[],a.length&&(this.lastPage=a[a.length-1].url,this.lastPageRid=t.rid);let c=this.state();return c.rid===t.rid&&this.states.save({...c,seq:t.seq+1}),this.parked&&(this.queue.length?this.persist():this.unpersist()),!0}retryLater(){this.failures++,this.retryTimer&&this.env.clearTimer(this.retryTimer),this.retryTimer=this.env.setTimer(()=>{this.retryTimer=null,this.flush()},d(this.failures))}stop(t){this.stopped=!0,this.queue=[],this.inflight=[],this.queuedBytes=0,this.clearTimers(),this.hooks.onStop(t)}clearTimers(){this.timer&&this.env.clearTimer(this.timer),this.retryTimer&&this.env.clearTimer(this.retryTimer),this.timer=this.retryTimer=null}persist(){let t=this.env.store,e=this.state(),r=this.inflight.concat(this.queue);!t||!e.rid||r.length===0||this.stopped||(this.parked=!0,t.set(S(this.ids.sid),{rid:e.rid,events:r}))}unpersist(){this.parked&&(this.parked=!1,_optionalChain([this, 'access', _38 => _38.env, 'access', _39 => _39.store, 'optionalAccess', _40 => _40.del, 'call', _41 => _41(S(this.ids.sid))]))}discard(){this.epoch++,this.stopped=!0,this.queue=[],this.inflight=[],this.queuedBytes=0,this.clearTimers(),this.unpersist()}get pendingEvents(){return this.queue.length+this.inflight.length}};var j="hm_rk_consent",K=i=>`rk:buf:${i}`,_t=500,wt=15e3,Ct=3,T=class{constructor(t,e=B()){this.options=t;this.ids=null;this.queue=null;this.collector=null;this.recorder=null;this.uploader=null;this.init=null;this.config=null;this.mode="idle";this.buffer=[];this.recent=[];this.stats=null;this.lastInputTs=0;this.earlyTrigger=null;this.destroyed=!1;this.offWindow=[];this.env=e;let r=(t.apiUrl||"https://app.himetrica.com").replace(/\/+$/,"");this.api=new m(e,r,t.apiKey),this.states=new p(e)}log(...t){this.options.debug&&console.debug("[ReplayKit]",...t)}start(){if(!L||!this.options.apiKey)return;let t=location.hostname;if(!this.options.allowLocalhost&&(t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost"))){this.log("localhost: idle (allowLocalhost to enable)");return}let e=this.env.now(),r=()=>{if(this.destroyed)return;let s=N(this.env);s.sessionId&&s.visitorId?(this.ids={sid:s.sessionId,vid:s.visitorId},this.boot()):this.env.now()-e<wt?this.env.setTimer(r,_t):this.log("no tracker ids on this page: idle")};r()}boot(){let t=this.ids;this.queue=new v(this.env,this.api,()=>({...t,rid:this.mode==="live"?this.state().rid:void 0})),this.collector=new b({now:()=>this.env.now(),maskAllText:()=>_nullishCoalesce(_optionalChain([this, 'access', _42 => _42.config, 'optionalAccess', _43 => _43.maskAllText]), () => (!0)),signal:e=>this.onSignal(e),trigger:e=>this.trigger(e),input:(e,r)=>this.onInput(e,r),navigated:e=>this.onNavigate(e)}),this.collector.start(),this.listenPage(),this.callInit(1)}state(){return this.states.load(this.ids.sid)}async callInit(t){let e=this.ids,r=await this.api.init({sid:e.sid,vid:e.vid,url:u(location.href)});if(!this.destroyed){if(r.outcome==="ok"&&r.data)return this.applyInit(r.data);if(r.outcome==="retry"&&t<Ct){this.env.setTimer(()=>{this.callInit(t+1)},d(t));return}if(this.log("init refused:",r.outcome),r.outcome==="quota"){_optionalChain([this, 'access', _44 => _44.queue, 'optionalAccess', _45 => _45.release, 'call', _46 => _46(!0)]),this.mode="off";return}this.shutdown()}}applyInit(t){if(this.init=t,this.config=t.config,this.queue.release(t.signals),!t.signals&&!t.record){this.shutdown();return}this.decide()}consentValue(){let t=this.env.getLocal(j);return t==="1"?!0:t==="0"?!1:null}triggerEnabled(t){return t==="manual"||t==="sample"?!0:!!_optionalChain([this, 'access', _47 => _47.config, 'optionalAccess', _48 => _48.triggers, 'access', _49 => _49.includes, 'call', _50 => _50(t)])}pathExcluded(){return x(_nullishCoalesce(_optionalChain([this, 'access', _51 => _51.config, 'optionalAccess', _52 => _52.excludePaths]), () => ([])),location.pathname)}onCheckoutPath(){return this.triggerEnabled("checkout")&&x(_nullishCoalesce(_optionalChain([this, 'access', _53 => _53.config, 'optionalAccess', _54 => _54.checkoutPaths]), () => ([])),location.pathname)}decide(){if(!this.init||!this.config)return;let t=this.state(),e=G({record:this.init.record,canGzip:!!this.env.gzip,state:t,excluded:this.pathExcluded(),requireConsent:this.config.requireConsent,consent:this.consentValue(),forceTrigger:this.init.forceTrigger,sampled:O(this.ids.sid,this.config.sampleRate),checkout:this.onCheckoutPath()});if(this.log("page:",e.kind,e.kind==="start"?e.trigger:""),e.kind==="off"||e.kind==="wait_consent"){this.mode=e.kind;return}if(e.kind==="continue"){this.mode="live";let r=_nullishCoalesce(t.stats, () => (E(this.env.now(),u(location.href))));this.stats={...r,pages:r.pages+1},this.makeUploader(),this.uploader.restorePending(),this.startRecorder();return}this.mode="buffer",this.restoreParkedBuffer().then(async()=>{if(this.mode!=="buffer"||(await this.startRecorder(),this.mode!=="buffer"))return;let r=e.kind==="start"?e.trigger:this.earlyTrigger;this.earlyTrigger=null,r&&this.triggerEnabled(r)&&this.promote(r)})}async restoreParkedBuffer(){let t=this.env.store;if(!t)return;let e=K(this.ids.sid),r=await t.get(e);if(!r)return;t.del(e),this.env.now()-r.at<w+f&&Array.isArray(r.events)&&r.events.length&&(this.buffer=r.events.concat(this.buffer))}async startRecorder(){if(this.recorder)return;let t=this.recorder=new k;!await t.start({blockSelectors:_nullishCoalesce(_optionalChain([this, 'access', _55 => _55.config, 'optionalAccess', _56 => _56.blockSelectors]), () => ([])),maskAllText:_nullishCoalesce(_optionalChain([this, 'access', _57 => _57.config, 'optionalAccess', _58 => _58.maskAllText]), () => (!1)),emit:r=>this.onEvent(r)})&&this.recorder===t&&(this.log("rrweb failed to start"),this.recorder=null,this.mode="off")}onEvent(t){if(this.mode==="buffer"){this.buffer.push(t),t.type===2&&(this.buffer=C(this.buffer,this.env.now()));return}this.mode==="live"&&this.uploader&&(this.stats&&(this.stats.endedAt=Math.max(this.stats.endedAt,t.timestamp)),this.uploader.add(t))}makeUploader(){this.uploader=new R(this.env,this.api,this.states,this.ids,{onStop:t=>this.stopRecording(t),beforeChunk:()=>this.saveStats()})}saveStats(){if(!this.stats||this.mode!=="live")return;let t=this.state();t.rid&&this.states.save({...t,stats:this.stats})}trigger(t){if(!(this.destroyed||!this.ids)){if(!this.init){this.earlyTrigger||(this.earlyTrigger=t);return}if(!(this.mode!=="buffer"||!this.triggerEnabled(t))){if(!this.recorder){_nullishCoalesce(this.earlyTrigger, () => ((this.earlyTrigger=t)));return}this.promote(t)}}}promote(t){let e=this.env.now(),r=this.buffer;this.buffer=[];let s=r.length?r[0].timestamp:e,n=E(s,u(location.href));n.endedAt=r.length?r[r.length-1].timestamp:e;let a=0;for(let o of this.recent)o.ts<s||(o.k==="click"?n.clicks++:o.k==="rage"?n.rageClicks++:o.k==="dead"?n.deadClicks++:o.k==="error"&&n.errors++,(o.k==="click"||o.k==="input")&&(n.activeMs+=A(a,o.ts),a=o.ts));this.recent=[],this.stats=n,this.states.save({...this.state(),rid:this.env.uuid(),seq:0,trigger:t,stats:n,stopped:void 0}),this.mode="live",this.log("recording:",t),this.makeUploader(),this.uploader.addMany(r),r.length||_optionalChain([this, 'access', _59 => _59.recorder, 'optionalAccess', _60 => _60.snapshot, 'call', _61 => _61()]),this.uploader.flush()}stopRecording(t){this.log("recording stopped:",t),_optionalChain([this, 'access', _62 => _62.recorder, 'optionalAccess', _63 => _63.stop, 'call', _64 => _64()]),this.recorder=null,this.mode="off",this.buffer=[];let e=this.state();this.states.save({...e,stopped:t})}onSignal(t){if(this.mode==="live"&&this.stats)t.type==="rage_click"?this.stats.rageClicks++:t.type==="dead_click"?this.stats.deadClicks++:t.type==="error"&&this.stats.errors++;else if(this.mode==="buffer"||this.mode==="idle"){let e=t.type==="rage_click"?"rage":t.type==="dead_click"?"dead":t.type==="error"?"error":null;e&&this.pushRecent(e,t.ts)}_optionalChain([this, 'access', _65 => _65.queue, 'optionalAccess', _66 => _66.add, 'call', _67 => _67(t)])}onInput(t,e){this.mode==="live"&&this.stats?(this.stats.activeMs+=A(this.lastInputTs,e),t==="click"&&this.stats.clicks++):(this.mode==="buffer"||this.mode==="idle")&&this.pushRecent(t==="click"?"click":"input",e),this.lastInputTs=e}pushRecent(t,e){this.recent.push({k:t,ts:e}),this.recent.length>1e3&&this.recent.splice(0,this.recent.length-1e3)}onNavigate(t){if(!this.init||!this.config)return;this.mode==="live"&&this.stats&&this.stats.pages++;let e=this.pathExcluded();if(e&&(this.mode==="live"||this.mode==="buffer")){_optionalChain([this, 'access', _68 => _68.recorder, 'optionalAccess', _69 => _69.stop, 'call', _70 => _70()]),this.recorder=null,this.mode==="buffer"&&(this.buffer=[]),_optionalChain([this, 'access', _71 => _71.uploader, 'optionalAccess', _72 => _72.flush, 'call', _73 => _73()]),this.mode="off";return}if(!e&&this.mode==="off"&&!this.state().stopped){this.uploader=null,this.decide();return}_optionalChain([this, 'access', _74 => _74.recorder, 'optionalAccess', _75 => _75.page, 'call', _76 => _76(t)]),this.onCheckoutPath()&&this.trigger("checkout")}listenPage(){let t=s=>{if(s&&_optionalChain([this, 'access', _77 => _77.collector, 'optionalAccess', _78 => _78.pageHide, 'call', _79 => _79()]),_optionalChain([this, 'access', _80 => _80.queue, 'optionalAccess', _81 => _81.beacon, 'call', _82 => _82()]),this.mode==="live")this.saveStats(),_optionalChain([this, 'access', _83 => _83.uploader, 'optionalAccess', _84 => _84.persist, 'call', _85 => _85()]);else if(this.mode==="buffer"&&this.buffer.length&&this.env.store){let n=C(this.buffer,this.env.now());this.env.store.set(K(this.ids.sid),{at:this.env.now(),events:n})}},e=()=>{document.visibilityState==="hidden"?t(!1):_optionalChain([this, 'access', _86 => _86.uploader, 'optionalAccess', _87 => _87.unpersist, 'call', _88 => _88()])},r=()=>t(!0);document.addEventListener("visibilitychange",e),window.addEventListener("pagehide",r),this.offWindow.push(()=>document.removeEventListener("visibilitychange",e),()=>window.removeEventListener("pagehide",r))}manualStart(t){if(this.ids){if(t&&this.log("manual trigger:",t),this.state().stopped==="manual"){this.states.save({...this.state(),stopped:void 0,rid:void 0,seq:0,trigger:void 0,stats:void 0}),this.uploader=null,this.earlyTrigger="manual",this.decide();return}this.trigger("manual")}}manualStop(){this.ids&&(_optionalChain([this, 'access', _89 => _89.recorder, 'optionalAccess', _90 => _90.stop, 'call', _91 => _91()]),this.recorder=null,this.buffer=[],this.mode==="live"&&(this.saveStats(),_optionalChain([this, 'access', _92 => _92.uploader, 'optionalAccess', _93 => _93.flush, 'call', _94 => _94()])),this.mode="off",this.states.save({...this.state(),stopped:"manual"}))}consent(t){if(this.env.setLocal(j,t?"1":"0"),!!this.ids){if(t){this.mode==="wait_consent"&&this.decide();return}_optionalChain([this, 'access', _95 => _95.recorder, 'optionalAccess', _96 => _96.stop, 'call', _97 => _97()]),this.recorder=null,this.buffer=[],_optionalChain([this, 'access', _98 => _98.uploader, 'optionalAccess', _99 => _99.discard, 'call', _100 => _100()]),_optionalChain([this, 'access', _101 => _101.env, 'access', _102 => _102.store, 'optionalAccess', _103 => _103.del, 'call', _104 => _104(K(this.ids.sid))]),this.mode="off"}}recordingId(){return this.mode==="live"&&this.ids?_nullishCoalesce(this.state().rid, () => (null)):null}shutdown(){_optionalChain([this, 'access', _105 => _105.collector, 'optionalAccess', _106 => _106.stop, 'call', _107 => _107()]),_optionalChain([this, 'access', _108 => _108.queue, 'optionalAccess', _109 => _109.disable, 'call', _110 => _110()]),_optionalChain([this, 'access', _111 => _111.recorder, 'optionalAccess', _112 => _112.stop, 'call', _113 => _113()]),this.recorder=null,this.mode="off"}destroy(){this.destroyed=!0,this.shutdown();for(let t of this.offWindow)t();this.offWindow=[]}};var h=null;function he(i){h||(h=new T(i),h.start())}function ce(){_optionalChain([h, 'optionalAccess', _114 => _114.manualStart, 'call', _115 => _115()])}function de(i){_optionalChain([h, 'optionalAccess', _116 => _116.manualStart, 'call', _117 => _117(i)])}function pe(){_optionalChain([h, 'optionalAccess', _118 => _118.manualStop, 'call', _119 => _119()])}function fe(i){if(h)h.consent(i);else try{localStorage.setItem("hm_rk_consent",i?"1":"0")}catch (e22){}}function ge(){return _nullishCoalesce(_optionalChain([h, 'optionalAccess', _120 => _120.recordingId, 'call', _121 => _121()]), () => (null))}function me(){_optionalChain([h, 'optionalAccess', _122 => _122.destroy, 'call', _123 => _123()]),h=null}exports.consent = fe; exports.getRecordingId = ge; exports.init = he; exports.shutdown = me; exports.start = ce; exports.stop = pe; exports.trigger = de;
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/state.ts","../src/env.ts","../src/identity.ts","../src/match.ts","../src/buffer.ts","../src/detect.ts","../src/decide.ts","../src/transport.ts"],"names":["KEY","StateStore","env","sid","s","raw","emptyStats","now","entryUrl","isBrowser","uuidV4","c","ch","r","safeGet","storage","key","safeSet","value","indexedDbStore","dbp","open","resolve","reject","req","run","mode","fn","db","tx","gzipFn","text","browserEnv","originalFetch","nav","url","body","name","match","ms","h","readIdentity","visitorId","sessionId","matchPath","pattern","pathname","p","path","base","escapeRegExp","matchAny","patterns","sampleDraw","h1","h2","i","inSample","rate","stripUrl","href","cut","PAGE_TAG","pagesOf","events","prev","max","out","last","e","d","BUFFER_WINDOW_MS","CHECKOUT_MS","snapshotStart","trimBuffer","windowMs","cutoff","keepFrom","firstSnapshot","start","approxBytes","RageDetector","b","near","finished","a","DEAD_CLICK_WAIT_MS","isDeadClickCandidate","f","isDeadClick","ACTIVE_GAP_MS","activeIncrement","lastInputTs","ts","gap","decidePage","outcomeOf","status","Api","apiUrl","apiKey","op"],"mappings":"AAuBA,u8BAAMA,CAAAA,CAAM,aAAA,CAECC,CAAAA,CAAN,KAAiB,CAGtB,WAAA,CAA6BC,CAAAA,CAAU,CAAV,IAAA,CAAA,GAAA,CAAAA,CAAAA,CAF7B,IAAA,CAAQ,KAAA,CAA6B,IAEG,CAExC,IAAA,CAAKC,CAAAA,CAA2B,CAC9B,EAAA,iBAAI,IAAA,qBAAK,KAAA,6BAAO,KAAA,GAAQA,CAAAA,CAAK,OAAO,IAAA,CAAK,KAAA,CACzC,IAAIC,CAAAA,CAAyB,IAAA,CAC7B,GAAI,CACF,IAAMC,CAAAA,CAAM,IAAA,CAAK,GAAA,CAAI,UAAA,CAAWL,CAAG,CAAA,CAC/BK,CAAAA,EAAAA,CAAKD,CAAAA,CAAI,IAAA,CAAK,KAAA,CAAMC,CAAG,CAAA,CAC7B,CAAA,UAAQ,CACND,CAAAA,CAAI,IACN,CACA,MAAA,CAAI,CAACA,CAAAA,EAAKA,CAAAA,CAAE,GAAA,GAAQD,CAAAA,EAAO,OAAOC,CAAAA,CAAE,GAAA,EAAQ,QAAA,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AA,CACtG,CAAA,CAAE,cAAA,EAAkB,CAAA,CAAE,OAAA,GAAY,CAAA,CAAA,CAAa,CAAE,IAAA,CAAM,cAAe,CAAA,CACtE,CAAA,CAAE,KAAA,CAAM,GAAA,CAAY,CAAE,IAAA,CAAM,UAAW,CAAA,CACvC,CAAA,CAAE,YAAA,CAAqB,CAAE,IAAA,CAAM,OAAA,CAAS,OAAA,CAAS,CAAA,CAAE,YAAa,CAAA,CAChE,CAAA,CAAE,QAAA,CAAiB,CAAE,IAAA,CAAM,OAAA,CAAS,OAAA,CAAS,UAAW,CAAA,CACxD,CAAA,CAAE,OAAA,CAAgB,CAAE,IAAA,CAAM,OAAA,CAAS,OAAA,CAAS,QAAS,CAAA,CAClD,CAAE,IAAA,CAAM,QAAS,CAC1B,CCrBO,SAASC,EAAAA,CAAUC,CAAAA,CAAyB,CACjD,OAAIA,CAAAA,EAAU,GAAA,EAAOA,CAAAA,CAAS,GAAA,CAAY,IAAA,CACtCA,CAAAA,GAAW,GAAA,CAAY,MAAA,CACvBA,CAAAA,GAAW,GAAA,CAAY,KAAA,CACvBA,CAAAA,GAAW,GAAA,CAAY,OAAA,CACvBA,CAAAA,GAAW,GAAA,EAAOA,CAAAA,GAAW,GAAA,EAAOA,CAAAA,GAAW,GAAA,EAAOA,CAAAA,GAAW,GAAA,CAAY,MAAA,CAC1E,OACT,CAOO,IAAMC,CAAAA,CAAN,KAAU,CACf,WAAA,CACmBhG,CAAAA,CACAiG,CAAAA,CACAC,CAAAA,CACjB,CAHiB,IAAA,CAAA,GAAA,CAAAlG,CAAAA,CACA,IAAA,CAAA,MAAA,CAAAiG,CAAAA,CACA,IAAA,CAAA,MAAA,CAAAC,CAChB,CAEH,GAAA,CAAIC,CAAAA,CAA0C,CAC5C,MAAO,CAAA,EAAA","file":"/home/runner/work/himetrica-replaykit/himetrica-replaykit/dist/index.cjs","sourcesContent":["// Per-session recording state, in sessionStorage so it follows the session across the\n// pages of a multi-page site (each page load is a new SDK instance).\n//\n// Keyed to the tracker session id: when the tracker rolls a new session (30 min idle,\n// new UTM...), the stored state belongs to the old one and is discarded.\n\nimport type { Env } from \"./env\";\nimport type { ReplayKitRecordingStats, ReplayKitTrigger } from \"./protocol\";\n\nexport type StopReason = \"quota\" | \"manual\" | \"limit\" | \"off\";\n\nexport interface SessionState {\n sid: string;\n /** Recording id, set once a trigger fired; absent while only buffering. */\n rid?: string;\n /** Next chunk sequence number to upload. */\n seq: number;\n trigger?: ReplayKitTrigger;\n /** Set when recording must not (re)start for the rest of the session. */\n stopped?: StopReason;\n stats?: ReplayKitRecordingStats;\n}\n\nconst KEY = \"hm_rk_state\";\n\nexport class StateStore {\n private cache: SessionState | null = null;\n\n constructor(private readonly env: Env) {}\n\n load(sid: string): SessionState {\n if (this.cache?.sid === sid) return this.cache;\n let s: SessionState | null = null;\n try {\n const raw = this.env.getSession(KEY);\n if (raw) s = JSON.parse(raw) as SessionState;\n } catch {\n s = null;\n }\n if (!s || s.sid !== sid || typeof s.seq !== \"number\") s = { sid, seq: 0 };\n this.cache = s;\n return s;\n }\n\n save(s: SessionState): void {\n this.cache = s;\n try {\n this.env.setSession(KEY, JSON.stringify(s));\n } catch {\n // In-memory copy still drives this page.\n }\n }\n}\n\nexport function emptyStats(now: number, entryUrl: string): ReplayKitRecordingStats {\n return { startedAt: now, endedAt: now, activeMs: 0, clicks: 0, rageClicks: 0, deadClicks: 0, errors: 0, pages: 1, entryUrl };\n}\n","// Browser globals behind one interface, like ErrorKit's env.ts.\n//\n// Network, storage, timers and the clock go through an Env, so the transport, the\n// uploader and the client run in plain Node under node:test with fakes. DOM wiring\n// (listeners, rrweb) stays in signals-dom.ts / recorder.ts and is not unit-tested.\n\nexport interface FetchResult {\n status: number;\n headers: { get(name: string): string | null };\n json(): Promise<unknown>;\n}\n\nexport interface Env {\n now(): number;\n uuid(): string;\n fetch?: (url: string, init: RequestInit) => Promise<FetchResult>;\n sendBeacon?: (url: string, body: string) => boolean;\n getLocal(key: string): string | null;\n setLocal(key: string, value: string | null): void;\n getSession(key: string): string | null;\n setSession(key: string, value: string | null): void;\n getCookie(name: string): string | null;\n /** Async key/value store that survives a page load (IndexedDB). Missing = nothing carried across pages. */\n store?: KvStore;\n /** gzip; undefined when CompressionStream is unavailable (recording is then skipped). */\n gzip?: (text: string) => Promise<Blob>;\n setTimer(fn: () => void, ms: number): unknown;\n clearTimer(handle: unknown): void;\n}\n\nexport interface KvStore {\n get<T>(key: string): Promise<T | undefined>;\n set(key: string, value: unknown): Promise<void>;\n del(key: string): Promise<void>;\n}\n\nexport const isBrowser = typeof window !== \"undefined\" && typeof document !== \"undefined\";\n\nexport function uuidV4(): string {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (c && typeof c.randomUUID === \"function\") {\n try {\n return c.randomUUID();\n } catch {\n // randomUUID throws on insecure origins in some browsers; fall through.\n }\n }\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (ch) => {\n const r = (Math.random() * 16) | 0;\n return (ch === \"x\" ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n\n// Storage throws in Safari private mode, sandboxed iframes and under storage policies.\nfunction safeGet(storage: () => Storage, key: string): string | null {\n try {\n return storage().getItem(key);\n } catch {\n return null;\n }\n}\n\nfunction safeSet(storage: () => Storage, key: string, value: string | null): void {\n try {\n if (value === null) storage().removeItem(key);\n else storage().setItem(key, value);\n } catch {\n // Unavailable or full: in-memory state still works for this page.\n }\n}\n\n/** One IndexedDB object store used as a key/value map. Every failure degrades to \"nothing stored\". */\nfunction indexedDbStore(): KvStore | undefined {\n if (typeof indexedDB === \"undefined\") return undefined;\n let dbp: Promise<IDBDatabase> | null = null;\n const open = () =>\n (dbp ??= new Promise<IDBDatabase>((resolve, reject) => {\n const req = indexedDB.open(\"himetrica-replaykit\", 1);\n req.onupgradeneeded = () => req.result.createObjectStore(\"kv\");\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n }));\n const run = <T>(mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest | void): Promise<T | undefined> =>\n open()\n .then(\n (db) =>\n new Promise<T | undefined>((resolve) => {\n const tx = db.transaction(\"kv\", mode);\n const req = fn(tx.objectStore(\"kv\"));\n tx.oncomplete = () => resolve(req ? (req.result as T) : undefined);\n tx.onerror = tx.onabort = () => resolve(undefined);\n }),\n )\n .catch(() => undefined);\n return {\n get: <T>(key: string) => run<T>(\"readonly\", (s) => s.get(key)),\n set: (key, value) => run<void>(\"readwrite\", (s) => void s.put(value, key)).then(() => undefined),\n del: (key) => run<void>(\"readwrite\", (s) => void s.delete(key)).then(() => undefined),\n };\n}\n\nfunction gzipFn(): Env[\"gzip\"] {\n if (typeof CompressionStream === \"undefined\" || typeof Blob === \"undefined\" || typeof Response === \"undefined\") return undefined;\n return (text) => new Response(new Blob([text]).stream().pipeThrough(new CompressionStream(\"gzip\"))).blob();\n}\n\nexport function browserEnv(): Env {\n const originalFetch = typeof fetch === \"function\" ? fetch.bind(globalThis) : undefined;\n const nav = typeof navigator !== \"undefined\" ? navigator : undefined;\n return {\n now: () => Date.now(),\n uuid: () => uuidV4(),\n fetch: originalFetch as Env[\"fetch\"],\n sendBeacon:\n nav && typeof nav.sendBeacon === \"function\"\n ? (url, body) => {\n try {\n return nav.sendBeacon(url, new Blob([body], { type: \"text/plain\" }));\n } catch {\n return false;\n }\n }\n : undefined,\n getLocal: (key) => safeGet(() => localStorage, key),\n setLocal: (key, value) => safeSet(() => localStorage, key, value),\n getSession: (key) => safeGet(() => sessionStorage, key),\n setSession: (key, value) => safeSet(() => sessionStorage, key, value),\n getCookie: (name) => {\n try {\n const match = document.cookie.match(new RegExp(\"(?:^|; )\" + name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") + \"=([^;]*)\"));\n return match ? decodeURIComponent(match[1]) : null;\n } catch {\n return null;\n }\n },\n store: indexedDbStore(),\n gzip: gzipFn(),\n setTimer: (fn, ms) => setTimeout(fn, ms),\n clearTimer: (h) => clearTimeout(h as ReturnType<typeof setTimeout>),\n };\n}\n","// Identity bridge with the analytics tracker, strictly READ-ONLY (same approach as\n// ErrorKit's browser/identity.ts).\n//\n// The tracker (tracker-js / tracker.js) stores the ids in:\n// visitor cookie hm_vid (cookieDomain mode) or localStorage hm_visitor_id\n// session cookie hm_sid (cookieDomain mode) or sessionStorage hm_session_id\n// We read those keys and never write them. window.himetrica.getSessionId() is NOT\n// called: in the tracker it refreshes the session timestamp.\n//\n// A recording or a signal is only worth something tied to the tracker's visitor and\n// session, so without the tracker on the page ReplayKit stays idle.\n\nimport type { Env } from \"./env\";\n\nexport interface Identity {\n visitorId?: string;\n sessionId?: string;\n}\n\nexport function readIdentity(env: Env): Identity {\n const visitorId = env.getCookie(\"hm_vid\") || env.getLocal(\"hm_visitor_id\") || undefined;\n const sessionId = env.getCookie(\"hm_sid\") || env.getSession(\"hm_session_id\") || undefined;\n return { visitorId, sessionId };\n}\n","// Pure helpers the recording decision is made of: path globs and the session sample.\n\n/**\n * Path glob, as the project config writes them: `*` matches any run of characters\n * (slashes included), everything else is literal. A pattern without `*` is a prefix\n * on a segment boundary: `/checkout` matches `/checkout` and `/checkout/step-2`, not\n * `/checkouts`. Matched against the pathname only, case-insensitive.\n */\nexport function matchPath(pattern: string, pathname: string): boolean {\n const p = pattern.trim().toLowerCase();\n if (!p) return false;\n const path = (pathname || \"/\").toLowerCase();\n if (!p.includes(\"*\")) {\n const base = p.endsWith(\"/\") && p.length > 1 ? p.slice(0, -1) : p;\n return path === base || path.startsWith(base.endsWith(\"/\") ? base : base + \"/\");\n }\n const re = new RegExp(\"^\" + p.split(\"*\").map(escapeRegExp).join(\".*\") + \"$\");\n return re.test(path);\n}\n\nexport function matchAny(patterns: readonly string[], pathname: string): boolean {\n for (const p of patterns) if (matchPath(p, pathname)) return true;\n return false;\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Deterministic [0, 1) from the session id (cyrb53). Every page of a session gets the\n * same draw, so a sampled session is recorded across all its pages, and the server\n * could recompute it.\n */\nexport function sampleDraw(sessionId: string): number {\n let h1 = 0xdeadbeef;\n let h2 = 0x41c6ce57;\n for (let i = 0; i < sessionId.length; i++) {\n const ch = sessionId.charCodeAt(i);\n h1 = Math.imul(h1 ^ ch, 2654435761);\n h2 = Math.imul(h2 ^ ch, 1597334677);\n }\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n const n = 4294967296 * (2097151 & h2) + (h1 >>> 0);\n return n / 9007199254740992;\n}\n\nexport function inSample(sessionId: string, rate: number): boolean {\n if (!(rate > 0)) return false;\n if (rate >= 1) return true;\n return sampleDraw(sessionId) < rate;\n}\n\n/** URL without query and hash: queries carry tokens and emails, never sent. */\nexport function stripUrl(href: string): string {\n const cut = href.search(/[?#]/);\n return cut === -1 ? href : href.slice(0, cut);\n}\n","// The pre-trigger ring buffer.\n//\n// rrweb can only replay from a full snapshot: a Meta event (type 4) followed by a\n// FullSnapshot (type 2). The recorder takes one every CHECKOUT_MS, so the buffer can\n// always be cut at the last checkout that is older than the window and still start\n// with a replayable page. The cut keeps BUFFER_WINDOW_MS..BUFFER_WINDOW_MS+CHECKOUT_MS\n// of history before the trigger.\n\nexport interface RrEvent {\n type: number;\n timestamp: number;\n data?: unknown;\n}\n\nexport const EVENT_FULL_SNAPSHOT = 2;\nexport const EVENT_META = 4;\nexport const EVENT_CUSTOM = 5;\n/** rrweb custom event the SDK adds on SPA URL changes (rrweb only emits Meta on page loads/checkouts). */\nexport const PAGE_TAG = \"replaykit:page\";\n\n/**\n * Pages shown in a run of events, in order: Meta hrefs (page loads, and every\n * checkout repeats the current one) plus PAGE_TAG custom events. Query/fragment\n * stripped, back-to-back repeats folded, `prev` = last page already reported for\n * this recording (so a checkout's repeated Meta is not a new page). Capped at `max`.\n */\nexport function pagesOf(events: RrEvent[], prev: string, max: number): Array<{ url: string; ts: number }> {\n const out: Array<{ url: string; ts: number }> = [];\n let last = prev;\n for (const e of events) {\n let href: unknown;\n if (e.type === EVENT_META) href = (e.data as { href?: unknown } | undefined)?.href;\n else if (e.type === EVENT_CUSTOM) {\n const d = e.data as { tag?: unknown; payload?: { href?: unknown } } | undefined;\n if (d?.tag === PAGE_TAG) href = d.payload?.href;\n }\n if (typeof href !== \"string\" || !href) continue;\n const cut = href.search(/[?#]/);\n const url = (cut === -1 ? href : href.slice(0, cut)).slice(0, 500);\n if (url === last) continue;\n last = url;\n out.push({ url, ts: e.timestamp });\n if (out.length >= max) break;\n }\n return out;\n}\n\nexport const BUFFER_WINDOW_MS = 30_000;\nexport const CHECKOUT_MS = 30_000;\n\n/** Index of the Meta event that opens the snapshot the event list may start from. */\nfunction snapshotStart(events: RrEvent[], i: number): number {\n // rrweb emits Meta right before FullSnapshot; keep the Meta so the player knows the viewport.\n return i > 0 && events[i - 1].type === EVENT_META ? i - 1 : i;\n}\n\n/**\n * Drops everything before the most recent full snapshot whose timestamp is at or\n * before `now - windowMs`. If no snapshot is that old, nothing is dropped (the buffer\n * is still shorter than the window). A list that does not start with a snapshot (the\n * head was lost) is cut at its first snapshot, since nothing before it can replay.\n */\nexport function trimBuffer(events: RrEvent[], now: number, windowMs = BUFFER_WINDOW_MS): RrEvent[] {\n const cutoff = now - windowMs;\n let keepFrom = -1;\n let firstSnapshot = -1;\n for (let i = 0; i < events.length; i++) {\n if (events[i].type !== EVENT_FULL_SNAPSHOT) continue;\n if (firstSnapshot === -1) firstSnapshot = i;\n if (events[i].timestamp <= cutoff) keepFrom = i;\n else break;\n }\n if (keepFrom === -1) keepFrom = firstSnapshot;\n if (keepFrom === -1) return [];\n const start = snapshotStart(events, keepFrom);\n return start === 0 ? events : events.slice(start);\n}\n\n/** Rough serialized size, to cut chunks without stringifying on every event. */\nexport function approxBytes(e: RrEvent): number {\n // Mutations and snapshots dominate; JSON.stringify per event is acceptable: events\n // are stringified once here and the chunk is re-stringified once at flush.\n try {\n return JSON.stringify(e).length;\n } catch {\n return 0;\n }\n}\n","// Friction detectors, DOM-free so node:test can drive them with plain numbers.\n// signals-dom.ts feeds them real clicks and reports what they decide.\n\nexport interface ClickPoint {\n x: number;\n y: number;\n ts: number;\n /** Stable key of the clicked element (its selector), so a burst on one button counts even if the mouse drifts. */\n target: string;\n}\n\n/** 3+ clicks within RAGE_WINDOW_MS, on the same element or within RAGE_RADIUS_PX of the first. */\nexport const RAGE_MIN_CLICKS = 3;\nexport const RAGE_WINDOW_MS = 1000;\nexport const RAGE_RADIUS_PX = 30;\n\nexport interface RageBurst {\n first: ClickPoint;\n count: number;\n lastTs: number;\n}\n\n/**\n * Feeds clicks in order. `onClick` returns \"trigger\" on the click that turns a burst\n * into a rage click (the 3rd), so recording starts right away; the finished burst\n * (with its final count) comes out of `onClick` of the next unrelated click or of\n * `flush(now)` once the window has passed.\n */\nexport class RageDetector {\n private burst: RageBurst | null = null;\n\n onClick(c: ClickPoint): { trigger: boolean; finished: RageBurst | null } {\n const b = this.burst;\n if (b && c.ts - b.lastTs <= RAGE_WINDOW_MS && near(b.first, c)) {\n b.count++;\n b.lastTs = c.ts;\n return { trigger: b.count === RAGE_MIN_CLICKS, finished: null };\n }\n const finished = b && b.count >= RAGE_MIN_CLICKS ? b : null;\n this.burst = { first: c, count: 1, lastTs: c.ts };\n return { trigger: false, finished };\n }\n\n /** The burst that ended (quiet for the window) before `now`, if it was a rage click. */\n flush(now: number): RageBurst | null {\n const b = this.burst;\n if (!b || now - b.lastTs <= RAGE_WINDOW_MS) return null;\n this.burst = null;\n return b.count >= RAGE_MIN_CLICKS ? b : null;\n }\n\n /** Clicks of the current burst so far (a rage burst is not also a dead click). */\n currentCount(): number {\n return this.burst?.count ?? 0;\n }\n}\n\nfunction near(a: ClickPoint, b: ClickPoint): boolean {\n if (a.target && a.target === b.target) return true;\n return Math.abs(a.x - b.x) <= RAGE_RADIUS_PX && Math.abs(a.y - b.y) <= RAGE_RADIUS_PX;\n}\n\n/** How long after a click something must happen for the click not to be \"dead\". */\nexport const DEAD_CLICK_WAIT_MS = 500;\n\nexport interface ClickTargetFacts {\n /** Lowercase tag name of the clicked element. */\n tag: string;\n /** The element or an ancestor is a link/button/[role=button…]/[onclick]/summary. */\n insideInteractive: boolean;\n /** Text fields, selects, labels, contenteditable: a click there focuses, nothing else to expect. */\n isFormField: boolean;\n /** Computed cursor is \"pointer\": the page tells the user it is clickable. */\n pointerCursor: boolean;\n /** Text is selected after the click (the user was selecting, not clicking). */\n hasSelection: boolean;\n}\n\n/**\n * A click can only be dead when the element promised something: it is (inside) an\n * interactive element or shows a pointer cursor. A click on plain text or on a\n * background is not friction, whatever happens after it.\n */\nexport function isDeadClickCandidate(f: ClickTargetFacts): boolean {\n if (f.isFormField || f.hasSelection) return false;\n if (f.tag === \"html\" || f.tag === \"body\") return false;\n return f.insideInteractive || f.pointerCursor;\n}\n\nexport interface AfterClickReaction {\n /** DOM mutations observed in the wait window. */\n mutations: number;\n urlChanged: boolean;\n scrolled: boolean;\n focusChanged: boolean;\n /** The page is unloading (a navigation or a download started). */\n unloading: boolean;\n}\n\n/** Nothing reacted within DEAD_CLICK_WAIT_MS: the click was dead. */\nexport function isDeadClick(r: AfterClickReaction): boolean {\n return r.mutations === 0 && !r.urlChanged && !r.scrolled && !r.focusChanged && !r.unloading;\n}\n\n/** Active time: input gaps up to ACTIVE_GAP_MS count, longer gaps are idle. */\nexport const ACTIVE_GAP_MS = 5000;\n\nexport function activeIncrement(lastInputTs: number, ts: number): number {\n if (!lastInputTs) return 0;\n const gap = ts - lastInputTs;\n return gap > 0 && gap <= ACTIVE_GAP_MS ? gap : 0;\n}\n","// What this page does about recording, from what /init said and the session state.\n// Pure, so the whole decision table is unit-tested.\n\nimport type { ReplayKitTrigger } from \"./protocol\";\nimport type { SessionState } from \"./state\";\n\nexport type PageMode =\n /** Nothing is recorded on this page (signals may still flow). */\n | { kind: \"off\" }\n /** requireConsent and the banner has not said yes yet. */\n | { kind: \"wait_consent\" }\n /** A recording of this session is already running: continue it. */\n | { kind: \"continue\" }\n /** Start a recording now, for this reason. */\n | { kind: \"start\"; trigger: ReplayKitTrigger }\n /** Keep the pre-trigger buffer and wait for a trigger. */\n | { kind: \"buffer\" };\n\nexport interface DecideInput {\n /** /init answered record: true. */\n record: boolean;\n /** CompressionStream exists (chunks are gzip'd in the browser). */\n canGzip: boolean;\n state: SessionState;\n /** Path is in excludePaths. */\n excluded: boolean;\n requireConsent: boolean;\n /** Consent stored by ReplayKit.consent(): true, false, or never given. */\n consent: boolean | null;\n forceTrigger: ReplayKitTrigger | null;\n sampled: boolean;\n /** Path matched checkoutPaths and \"checkout\" is an enabled trigger. */\n checkout: boolean;\n}\n\nexport function decidePage(i: DecideInput): PageMode {\n // An explicit ReplayKit.consent(false) wins even when the project does not require consent.\n if (!i.record || !i.canGzip || i.state.stopped || i.excluded || i.consent === false) return { kind: \"off\" };\n if (i.requireConsent && i.consent !== true) return { kind: \"wait_consent\" };\n if (i.state.rid) return { kind: \"continue\" };\n if (i.forceTrigger) return { kind: \"start\", trigger: i.forceTrigger };\n if (i.checkout) return { kind: \"start\", trigger: \"checkout\" };\n if (i.sampled) return { kind: \"start\", trigger: \"sample\" };\n return { kind: \"buffer\" };\n}\n","// Calls to the ingest (POST {apiUrl}/api/t/r/<op>?apiKey=...), text/plain JSON so\n// they are \"simple\" CORS requests with no preflight, plus the PUT of a chunk to R2.\n//\n// Every response is reduced to an outcome the client acts on (see the contract in\n// packages/shared/src/replaykit.ts):\n// ok 2xx\n// drop 400/413: this body is unusable, forget it\n// stop 401: bad key / origin not allowed, ReplayKit stops for this page\n// off 403: rollout, plan or this op is off for the project\n// quota 429: no more recordings this session (signals continue)\n// retry 5xx, network error, or no fetch at all\n\nimport type { Env } from \"./env\";\nimport type {\n ReplayKitChunkRequest,\n ReplayKitChunkResponse,\n ReplayKitInitRequest,\n ReplayKitInitResponse,\n ReplayKitSignalsRequest,\n} from \"./protocol\";\n\nexport type Outcome = \"ok\" | \"drop\" | \"stop\" | \"off\" | \"quota\" | \"retry\";\n\nexport function outcomeOf(status: number): Outcome {\n if (status >= 200 && status < 300) return \"ok\";\n if (status === 401) return \"stop\";\n if (status === 403) return \"off\";\n if (status === 429) return \"quota\";\n if (status === 400 || status === 413 || status === 404 || status === 422) return \"drop\";\n return \"retry\";\n}\n\nexport interface Result<T> {\n outcome: Outcome;\n data?: T;\n}\n\nexport class Api {\n constructor(\n private readonly env: Env,\n private readonly apiUrl: string,\n private readonly apiKey: string,\n ) {}\n\n url(op: \"init\" | \"chunk\" | \"signals\"): string {\n return `${this.apiUrl}/api/t/r/${op}?apiKey=${encodeURIComponent(this.apiKey)}`;\n }\n\n init(body: ReplayKitInitRequest): Promise<Result<ReplayKitInitResponse>> {\n return this.post<ReplayKitInitResponse>(\"init\", body, true);\n }\n\n chunk(body: ReplayKitChunkRequest): Promise<Result<ReplayKitChunkResponse>> {\n return this.post<ReplayKitChunkResponse>(\"chunk\", body, true);\n }\n\n signals(body: ReplayKitSignalsRequest): Promise<Result<void>> {\n return this.post<void>(\"signals\", body, false);\n }\n\n /** On page hide: fire-and-forget. False when the beacon could not be queued. */\n beaconSignals(body: ReplayKitSignalsRequest): boolean {\n return !!this.env.sendBeacon?.(this.url(\"signals\"), JSON.stringify(body));\n }\n\n /** PUT the gzip'd chunk to the presigned R2 URL. R2 answers 200; 403 = URL expired or bad signature. */\n async put(url: string, blob: Blob): Promise<Outcome> {\n if (!this.env.fetch) return \"retry\";\n try {\n const res = await this.env.fetch(url, { method: \"PUT\", body: blob, headers: { \"Content-Type\": \"application/gzip\" } });\n if (res.status >= 200 && res.status < 300) return \"ok\";\n // An expired/rejected signature is fixed by asking for a new URL, not by dropping the chunk.\n return res.status === 400 || res.status === 413 ? \"drop\" : \"retry\";\n } catch {\n return \"retry\";\n }\n }\n\n private async post<T>(op: \"init\" | \"chunk\" | \"signals\", body: unknown, wantJson: boolean): Promise<Result<T>> {\n if (!this.env.fetch) return { outcome: \"retry\" };\n try {\n const res = await this.env.fetch(this.url(op), {\n method: \"POST\",\n body: JSON.stringify(body),\n headers: { \"Content-Type\": \"text/plain\" },\n keepalive: false,\n credentials: \"omit\",\n });\n const outcome = outcomeOf(res.status);\n if (outcome !== \"ok\" || !wantJson) return { outcome };\n try {\n return { outcome, data: (await res.json()) as T };\n } catch {\n return { outcome: \"retry\" };\n }\n } catch {\n return { outcome: \"retry\" };\n }\n }\n}\n\nexport const BASE_BACKOFF_MS = 2_000;\nexport const MAX_BACKOFF_MS = 60_000;\n\nexport function backoff(failures: number): number {\n return Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * 2 ** Math.max(0, failures - 1));\n}\n"]}
@@ -0,0 +1,46 @@
1
+ type ReplayKitTrigger = "error" | "rage_click" | "checkout" | "paying" | "sample" | "manual";
2
+ type ReplayKitSignalType = "rage_click" | "dead_click" | "error" | "back_nav" | "form_abandon";
3
+ interface ReplayKitSignal {
4
+ type: ReplayKitSignalType;
5
+ ts: number;
6
+ url: string;
7
+ selector?: string;
8
+ text?: string;
9
+ count?: number;
10
+ detail?: string;
11
+ }
12
+
13
+ interface ReplayKitOptions {
14
+ /** Your project's public API key (the same one the tracker uses). */
15
+ apiKey: string;
16
+ /** Defaults to https://app.himetrica.com. */
17
+ apiUrl?: string;
18
+ /** Run on localhost (off by default, like the tracker). */
19
+ allowLocalhost?: boolean;
20
+ /** Log decisions to the console. */
21
+ debug?: boolean;
22
+ }
23
+
24
+ /** Starts ReplayKit. A second call is ignored. */
25
+ declare function init(options: ReplayKitOptions): void;
26
+ /** Record this session from now on (and keep the pre-trigger buffer). */
27
+ declare function start(): void;
28
+ /**
29
+ * Mark this moment as worth a recording, like an error would. `reason` is for your
30
+ * own debugging (logged with `debug: true`); the recording is tagged "manual".
31
+ */
32
+ declare function trigger(reason?: string): void;
33
+ /** Stop recording for the rest of the session. What was captured is still uploaded. */
34
+ declare function stop(): void;
35
+ /**
36
+ * The visitor's answer to your consent banner. With "require consent" on in the
37
+ * project, nothing is recorded until consent(true). consent(false) stops and drops
38
+ * what was not uploaded yet. Remembered on this device.
39
+ */
40
+ declare function consent(granted: boolean): void;
41
+ /** Id of the recording running on this page, if any. */
42
+ declare function getRecordingId(): string | null;
43
+ /** Stops everything and removes the listeners (tests, SPA teardown). */
44
+ declare function shutdown(): void;
45
+
46
+ export { type ReplayKitOptions, type ReplayKitSignal, type ReplayKitSignalType, type ReplayKitTrigger, consent, getRecordingId, init, shutdown, start, stop, trigger };
@@ -0,0 +1,46 @@
1
+ type ReplayKitTrigger = "error" | "rage_click" | "checkout" | "paying" | "sample" | "manual";
2
+ type ReplayKitSignalType = "rage_click" | "dead_click" | "error" | "back_nav" | "form_abandon";
3
+ interface ReplayKitSignal {
4
+ type: ReplayKitSignalType;
5
+ ts: number;
6
+ url: string;
7
+ selector?: string;
8
+ text?: string;
9
+ count?: number;
10
+ detail?: string;
11
+ }
12
+
13
+ interface ReplayKitOptions {
14
+ /** Your project's public API key (the same one the tracker uses). */
15
+ apiKey: string;
16
+ /** Defaults to https://app.himetrica.com. */
17
+ apiUrl?: string;
18
+ /** Run on localhost (off by default, like the tracker). */
19
+ allowLocalhost?: boolean;
20
+ /** Log decisions to the console. */
21
+ debug?: boolean;
22
+ }
23
+
24
+ /** Starts ReplayKit. A second call is ignored. */
25
+ declare function init(options: ReplayKitOptions): void;
26
+ /** Record this session from now on (and keep the pre-trigger buffer). */
27
+ declare function start(): void;
28
+ /**
29
+ * Mark this moment as worth a recording, like an error would. `reason` is for your
30
+ * own debugging (logged with `debug: true`); the recording is tagged "manual".
31
+ */
32
+ declare function trigger(reason?: string): void;
33
+ /** Stop recording for the rest of the session. What was captured is still uploaded. */
34
+ declare function stop(): void;
35
+ /**
36
+ * The visitor's answer to your consent banner. With "require consent" on in the
37
+ * project, nothing is recorded until consent(true). consent(false) stops and drops
38
+ * what was not uploaded yet. Remembered on this device.
39
+ */
40
+ declare function consent(granted: boolean): void;
41
+ /** Id of the recording running on this page, if any. */
42
+ declare function getRecordingId(): string | null;
43
+ /** Stops everything and removes the listeners (tests, SPA teardown). */
44
+ declare function shutdown(): void;
45
+
46
+ export { type ReplayKitOptions, type ReplayKitSignal, type ReplayKitSignalType, type ReplayKitTrigger, consent, getRecordingId, init, shutdown, start, stop, trigger };