@faststats/web 0.2.14 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/api-urls-nKmJnyjD.js +1 -0
- package/dist/chunks/identifiers-DrjjHcKB.js +1 -0
- package/dist/chunks/{replay-DvJYurEC.d.ts → replay-DR_T0Iz4.d.ts} +12 -17
- package/dist/chunks/send-data-Cb4xlYF0.js +1 -0
- package/dist/error.d.ts +4 -12
- package/dist/error.js +2 -1
- package/dist/feature-flags.d.ts +19 -2
- package/dist/feature-flags.js +1 -1
- package/dist/index.d.ts +28 -59
- package/dist/index.js +1 -1
- package/dist/replay.d.ts +2 -2
- package/dist/replay.js +1 -1
- package/dist/web-vitals.d.ts +5 -8
- package/dist/web-vitals.js +1 -1
- package/package.json +7 -6
- package/CHANGELOG.md +0 -184
- package/REPLAY_PAYLOAD.md +0 -64
- package/dist/chunks/api-urls-DaeYkG0_.js +0 -1
- package/dist/chunks/error-Cd9PTS5v.js +0 -2
- package/dist/chunks/feature-flags-BClx56v5.d.ts +0 -19
- package/dist/chunks/feature-flags-DSOCIZHK.js +0 -1
- package/dist/chunks/replay-rTqcjOo2.js +0 -1
- package/dist/chunks/rolldown-runtime-MP-BAFHD.js +0 -1
- package/dist/chunks/send-data-B2fYGj6v.js +0 -1
- package/dist/chunks/session-manager-Cy63ptPF.js +0 -1
- package/dist/chunks/types-CYzR5xtT.js +0 -1
- package/dist/chunks/web-vitals-Be-Cg4Po.js +0 -1
- package/scripts/check-bundle-size.mjs +0 -96
- package/src/analytics.ts +0 -787
- package/src/entries/error.ts +0 -6
- package/src/entries/feature-flags.ts +0 -5
- package/src/entries/main.ts +0 -21
- package/src/entries/replay.ts +0 -1
- package/src/entries/web-vitals.ts +0 -1
- package/src/env.d.ts +0 -2
- package/src/error.ts +0 -257
- package/src/feature-flags.ts +0 -84
- package/src/replay.ts +0 -596
- package/src/sdk.ts +0 -8
- package/src/utils/api-urls.ts +0 -24
- package/src/utils/identifiers.ts +0 -47
- package/src/utils/send-data.ts +0 -52
- package/src/utils/session-manager.ts +0 -416
- package/src/utils/types.ts +0 -15
- package/src/web-vitals.ts +0 -159
- package/tests/analytics.test.ts +0 -453
- package/tests/identifiers.test.ts +0 -78
- package/tests/replay.test.ts +0 -582
- package/tests/session-manager.test.ts +0 -161
- package/tests/web-vitals.test.ts +0 -208
- package/tsconfig.json +0 -30
- package/tsdown.config.ts +0 -27
- package/worker/index.ts +0 -22
package/REPLAY_PAYLOAD.md
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
# `/v1/replay` payload
|
|
2
|
-
|
|
3
|
-
Session replay batches are sent as `POST` requests to `/v1/replay`, optionally gzip-compressed via `?encoding=gzip` with `Content-Type: application/octet-stream`.
|
|
4
|
-
|
|
5
|
-
## Request body (JSON)
|
|
6
|
-
|
|
7
|
-
```json
|
|
8
|
-
{
|
|
9
|
-
"token": "site_xxx",
|
|
10
|
-
"sessionId": "uuid",
|
|
11
|
-
"windowId": "uuid",
|
|
12
|
-
"viewId": "uuid",
|
|
13
|
-
"sessionStart": 1730000000000,
|
|
14
|
-
"identifier": "optional-anon-id",
|
|
15
|
-
"batchId": "{sessionId}-{sequence}-{random}",
|
|
16
|
-
"sequence": 0,
|
|
17
|
-
"timestamp": 1730000000500,
|
|
18
|
-
"url": "https://example.com/path",
|
|
19
|
-
"isFinal": false,
|
|
20
|
-
"events": []
|
|
21
|
-
}
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
## Fields
|
|
25
|
-
|
|
26
|
-
| Field | Type | Description |
|
|
27
|
-
|-------|------|-------------|
|
|
28
|
-
| `token` | string | Site / project key |
|
|
29
|
-
| `sessionId` | string | User session (localStorage, shared across tabs; 30m idle / 24h max rotation) |
|
|
30
|
-
| `windowId` | string | Browser tab (sessionStorage per site key; stable across SDK remounts in same tab) |
|
|
31
|
-
| `viewId` | string | Page view within tab (new UUID on each SPA/full navigation) |
|
|
32
|
-
| `sessionStart` | number | Session start time in ms since epoch |
|
|
33
|
-
| `identifier` | string? | Anonymous user id (omitted in cookieless mode) |
|
|
34
|
-
| `batchId` | string | Idempotent key for retries (`{sessionId}-{sequence}-{uuid}`) |
|
|
35
|
-
| `sequence` | number | Monotonic batch index per recorder instance |
|
|
36
|
-
| `timestamp` | number | Batch creation time (ms since epoch) |
|
|
37
|
-
| `url` | string | Page URL when the batch was created |
|
|
38
|
-
| `isFinal` | boolean? | `true` on last batch before session rotation or tab unload |
|
|
39
|
-
| `events` | array | rrweb `eventWithTime` records |
|
|
40
|
-
|
|
41
|
-
## Custom events in `events`
|
|
42
|
-
|
|
43
|
-
SPA navigations inject a custom rrweb event:
|
|
44
|
-
|
|
45
|
-
```json
|
|
46
|
-
{
|
|
47
|
-
"type": 5,
|
|
48
|
-
"timestamp": 1730000001000,
|
|
49
|
-
"data": {
|
|
50
|
-
"tag": "faststats:view",
|
|
51
|
-
"payload": {
|
|
52
|
-
"href": "https://example.com/about",
|
|
53
|
-
"viewId": "uuid"
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
## Ingestion guidelines
|
|
60
|
-
|
|
61
|
-
1. Stitch batches by `(token, sessionId, windowId, sequence)`; dedupe retries with `batchId`.
|
|
62
|
-
2. When `sessionId` changes and the prior batch had `isFinal: true`, finalize the previous recording segment.
|
|
63
|
-
3. Group events within a tab by `viewId` (and `faststats:view` meta events for href changes).
|
|
64
|
-
4. Legacy clients may send `pageId` instead of `viewId` and omit `sessionStart` / `isFinal` — treat as older SDK versions.
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=`https://metrics.faststats.dev`,t=`https://flags.faststats.dev`;function n(e){return e.replace(/\/+$/,``)}function r(t){return t===void 0||t===``?e:n(t)||e}const i={events:`/v1/web`,identify:`/v1/identify`,replay:`/v1/replay`,vitals:`/v1/vitals`,flags:`/v1/check`};function a(e){return e===void 0||e===``?t:n(e)||t}export{r as n,a as r,i as t};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-MP-BAFHD.js";import{n as t,t as n}from"./api-urls-DaeYkG0_.js";import{n as r,r as i}from"./session-manager-Cy63ptPF.js";import{n as a,t as o}from"./send-data-B2fYGj6v.js";var s=e({default:()=>m});const c=/(?:^|\()(chrome|moz|ms-browser|safari-web)-extension:\/\//,l=e=>e?.split(`
|
|
2
|
-
`).map(e=>e.trim()).filter(Boolean);function u(e){if(e instanceof Error)return{error:e.name?.trim()||`Error`,message:e.message,stack:l(e.stack),cause:u(e.cause)};if(typeof e==`string`)return{error:`Error`,message:e}}function d(e){let t=``;for(let n=e;n;n=n.cause)t+=`${n.error}\0${n.message??``}\0`;return t}function f(e){let t=2166136261,n=3598710387;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,16777619),n=Math.imul(n^i,2246822519)}return`err_${(t>>>0).toString(16).padStart(8,`0`)}${(n>>>0).toString(16).padStart(8,`0`)}`}function p(){let e=globalThis.__SOURCEMAPS_BUILD__?.buildId;return typeof e==`string`&&e.trim()?e:void 0}var m=class{endpoint;seen=new WeakSet;queue=new Map;timer=null;started=!1;flushing=!1;constructor(e){this.options=e,this.endpoint=`${t(e.baseUrl)}${n.events}`}log(...e){this.options.debug&&console.log(`[ErrorTracker]`,...e)}start(){this.started||typeof window>`u`||(this.started=!0,window.addEventListener(`error`,this.onError),window.addEventListener(`unhandledrejection`,this.onRejection),window.addEventListener(`pagehide`,this.scheduleFlush),document.addEventListener(`visibilitychange`,this.onVisibility),this.timer=setInterval(this.scheduleFlush,this.options.flushInterval??5e3),this.log(`Started`))}stop(){!this.started||typeof window>`u`||(this.started=!1,window.removeEventListener(`error`,this.onError),window.removeEventListener(`unhandledrejection`,this.onRejection),window.removeEventListener(`pagehide`,this.scheduleFlush),document.removeEventListener(`visibilitychange`,this.onVisibility),this.timer&&clearInterval(this.timer),this.timer=null,this.scheduleFlush(),this.log(`Stopped`))}captureError(e){this.capture(`error`,e.message,!0,e)}onError=e=>{this.capture(`error`,e.message||`Unknown error`,!1,e.error,e.filename||``,e.lineno)};onRejection=e=>{let t=e.reason,n=t instanceof Error?t.message:typeof t==`string`?t:`Unhandled promise rejection`;this.capture(`unhandledrejection`,n,!1,t)};onVisibility=()=>{document.visibilityState===`hidden`&&this.scheduleFlush()};scheduleFlush=()=>{this.flush()};capture(e,t,n,r,i=``,a=``){let o=r instanceof Error?r.stack??``:``;if(c.test(`${i}\n${o}`))return;if(typeof r==`object`&&r){if(this.seen.has(r)){this.log(`Skipping duplicate:`,t);return}this.seen.add(r)}let s={error:e===`unhandledrejection`?`UnhandledRejection`:`Error`,message:t,handled:n};if(r instanceof Error){s.stack=l(r.stack);let e=u(r.cause);e&&(s.cause=e)}let p=f(`${e}\0${n?`handled`:`unhandled`}\0${t}\0${i}\0${a}\0${d(s.cause)}`),m=this.queue.get(p);m?m.count++:this.queue.set(p,{hash:p,count:1,...s}),this.log(`Captured:`,s),this.queue.size>=(this.options.maxQueueSize??50)&&this.scheduleFlush()}async flush(){if(this.flushing||this.queue.size===0)return;let e=[...this.queue.values()];this.queue.clear(),this.flushing=!0;let t=a(),n=p(),s=JSON.stringify({token:this.options.siteKey,...t?{userId:t}:{},sessionId:r(),windowId:i(this.options.siteKey),...n?{buildId:n}:{},sdkName:this.options.sdkName??`@faststats/web`,sdkVersion:this.options.sdkVersion??`0.2.14`,data:{url:location.href,page:location.pathname,referrer:document.referrer||null,title:document.title},errors:e});this.log(`Flushing:`,e);try{await o({url:this.endpoint,data:s,debug:this.options.debug,debugPrefix:`[ErrorTracker]`})||this.requeue(e)}catch{this.requeue(e)}finally{this.flushing=!1}}requeue(e){for(let t of e){let e=this.queue.get(t.hash);e?e.count+=t.count:this.queue.set(t.hash,t)}}};export{s as n,m as t};
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
//#region src/feature-flags.d.ts
|
|
2
|
-
type FeatureFlagEvaluation = {
|
|
3
|
-
value: string;
|
|
4
|
-
variantKey?: string;
|
|
5
|
-
variantValue?: string;
|
|
6
|
-
};
|
|
7
|
-
type FeatureFlagCheckContext = {
|
|
8
|
-
baseUrl?: string;
|
|
9
|
-
projectToken?: string;
|
|
10
|
-
projectId?: string;
|
|
11
|
-
identifier?: string;
|
|
12
|
-
externalId?: string;
|
|
13
|
-
sessionId?: string;
|
|
14
|
-
attributes?: Record<string, unknown>;
|
|
15
|
-
signal?: AbortSignal;
|
|
16
|
-
};
|
|
17
|
-
declare function fetchFeatureFlagEvaluation(flagKey: string, context: FeatureFlagCheckContext): Promise<FeatureFlagEvaluation>;
|
|
18
|
-
//#endregion
|
|
19
|
-
export { FeatureFlagEvaluation as n, fetchFeatureFlagEvaluation as r, FeatureFlagCheckContext as t };
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-MP-BAFHD.js";import{r as t,t as n}from"./api-urls-DaeYkG0_.js";var r=e({fetchFeatureFlagEvaluation:()=>i});async function i(e,r){if(r.projectToken&&r.projectId)throw Error(`provide either projectToken or projectId, not both`);let i=r.projectToken,a=r.projectId,o=r.identifier,s=r.externalId,c=r.sessionId;if(!i&&!a)throw Error(`feature flag check requires projectToken or projectId`);if(!o&&!s)throw Error(`feature flag check requires serverId or externalId`);let l={key:e,...a?{projectId:a}:{},...o?{identifier:o}:{},...s?{externalId:s}:{},...c?{sessionId:c}:{}};r.attributes&&Object.keys(r.attributes).length>0&&(l.attributes=r.attributes);let u={"Content-Type":`application/json`};i&&(u.Authorization=`Bearer ${i}`);let d=`${t(r.baseUrl)}${n.flags}`,f=await fetch(d,{method:`POST`,headers:u,body:JSON.stringify(l),credentials:`omit`,signal:r.signal});if(!f.ok){let e=``;try{let t=await f.json();typeof t.error==`string`&&t.error.length>0&&(e=` — ${t.error}`)}catch{}throw Error(`feature flag check failed: HTTP ${f.status}${e}`)}return await f.json()}export{i as n,r as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-MP-BAFHD.js";import{n as t,t as n}from"./api-urls-DaeYkG0_.js";import{a as r,f as i,i as a,s as o,t as s}from"./session-manager-Cy63ptPF.js";import{n as c,t as l}from"./send-data-B2fYGj6v.js";import{t as u}from"./types-CYzR5xtT.js";import{EventType as d}from"@rrweb/types";import{record as f}from"rrweb";var p=e({default:()=>v});const m={mousemove:50,mouseInteraction:!0,scroll:150,media:800,input:`last`};function h(e){return`faststats_replay_sampled_${e}`}function g(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)}function _(e,t,n){let r=u(t);if(r>=100)return!0;if(r<=0)return!1;let i=a(e,n).sessionId,o=h(e),s=`${i}:${r}`;try{let e=sessionStorage;if(e){let t=e.getItem(o);if(t===s)return!0;if(t?.startsWith(`${i}:`))return!1}}catch{}let c=g(i)%100<r;try{sessionStorage?.setItem(o,c?s:`${i}:out`)}catch{}return c}var v=class{endpoint;compressionSupported=typeof window<`u`&&`CompressionStream`in window;sampled;events=[];pending=[];pendingSizeBytes=0;viewId=s();windowId=s();started=!1;startTime=0;sequence=0;intervalId=null;flushTask=null;retryTask=null;minLengthFlushTask=null;stopRecording;sending=!1;unsubscribeRotation;constructor(e){this.options=e,this.endpoint=`${t(e.baseUrl)}${n.replay}`,this.sampled=_(e.siteKey,e.samplingPercentage??100,e.cookieless??!1)}get cookieless(){return this.options.cookieless??!1}get debug(){return this.options.debug??!1}get flushInterval(){return this.options.flushInterval??1e4}get maxEvents(){return this.options.maxEvents??500}get maxPendingBatches(){return this.options.maxPendingBatches??30}get maxQueueSizeBytes(){return this.options.maxQueueSizeBytes??2097152}get minReplayLengthMs(){return this.options.minReplayLengthMs??3e3}get shouldCompress(){return this.options.compress??!0}log(...e){this.debug&&console.log(`[Replay]`,...e)}sessionContext(){return a(this.options.siteKey,this.cookieless)}start(){this.started||typeof window>`u`||!this.sampled||(this.started=!0,this.viewId=s(),this.startTime=r(this.cookieless),this.unsubscribeRotation=o(e=>{this.onSessionRotated(e)}),this.beginRecording(),this.intervalId=setInterval(this.requestFlush,this.flushInterval),window.addEventListener(`beforeunload`,this.onUnload),window.addEventListener(`pagehide`,this.onUnload),document.addEventListener(`visibilitychange`,this.onVisibilityChange),this.log(`Recording started`))}trackPageChange(e){if(!this.started)return;let t=e??window.location.href;this.viewId=s();let n={type:5,timestamp:Date.now(),data:{tag:`faststats:view`,payload:{href:t,viewId:this.viewId}}};this.onEvent(n,!1)}async beginRecording(){let e=this.options.recordConsole??!0?await import(`@rrweb/rrweb-plugin-console-record`):null;if(!this.started)return;let t=[];e&&t.push(e.getRecordConsolePlugin()),this.stopRecording=f({emit:this.onEvent,sampling:this.options.sampling??m,slimDOMOptions:this.options.slimDOMOptions??{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0},maskAllInputs:this.options.maskAllInputs??!0,maskInputOptions:this.options.maskInputOptions??{password:!0,email:!0,tel:!0},blockClass:this.options.blockClass,blockSelector:this.options.blockSelector,maskTextClass:this.options.maskTextClass,maskTextSelector:this.options.maskTextSelector,checkoutEveryNms:this.options.checkoutEveryNms??6e4,checkoutEveryNth:this.options.checkoutEveryNth,plugins:t})}stop(){if(this.started){if(this.started=!1,this.unsubscribeRotation?.(),this.unsubscribeRotation=void 0,this.stopRecording?.(),this.stopRecording=void 0,this.intervalId&&clearInterval(this.intervalId),this.flushTask&&clearTimeout(this.flushTask),this.retryTask&&clearTimeout(this.retryTask),this.minLengthFlushTask&&clearTimeout(this.minLengthFlushTask),this.intervalId=null,this.flushTask=null,this.retryTask=null,this.minLengthFlushTask=null,window.removeEventListener(`beforeunload`,this.onUnload),window.removeEventListener(`pagehide`,this.onUnload),document.removeEventListener(`visibilitychange`,this.onVisibilityChange),!this.hasReachedMinLength()){this.events.length=0,this.log(`Session too short (${Date.now()-this.startTime}ms), discarding events`);return}this.flush(!0,void 0,!0),this.log(`Recording stopped`)}}getSessionId(){return this.sessionContext().sessionId}getWindowId(){return this.sessionContext().windowId}onSessionRotated(e){if(this.started){if(this.events.length>0)if(!this.hasReachedMinLength())this.scheduleMinLengthFlush();else{let t=this.createBatch(this.events.splice(0),e,!0);this.enqueueBatch(t)}this.pending.length>0&&queueMicrotask(()=>void this.flush(!1))}}onEvent=(e,t)=>{if(this.events.push(e),t||this.events.length>=this.maxEvents||e.type===d.FullSnapshot&&this.hasReachedMinLength()){this.requestFlush();return}this.scheduleMinLengthFlush()};onUnload=()=>{this.flush(!0,void 0,!0)};onVisibilityChange=()=>{document.visibilityState===`hidden`&&this.flush(!0,void 0,!0)};hasReachedMinLength(){return this.minReplayLengthMs<=0||Date.now()-this.startTime>=this.minReplayLengthMs}requestFlush=()=>{this.flushTask||this.sending||this.events.length===0||(this.minLengthFlushTask&&=(clearTimeout(this.minLengthFlushTask),null),this.flushTask=setTimeout(()=>{this.flushTask=null,this.flush(!1)},0))};scheduleMinLengthFlush(){if(this.minLengthFlushTask||this.events.length===0||this.hasReachedMinLength())return;let e=Math.max(0,this.minReplayLengthMs-(Date.now()-this.startTime)),t=Math.min(e,2147483647);this.minLengthFlushTask=setTimeout(()=>{this.minLengthFlushTask=null,this.requestFlush()},t)}createBatch(e,t,n){let r=c(this.cookieless),i=this.sequence++;return{token:this.options.siteKey,sessionId:t.sessionId,windowId:this.windowId,viewId:this.viewId,sessionStart:t.sessionStart,...r?{identifier:r}:{},batchId:this.createBatchId(t.sessionId,i),sequence:i,timestamp:Date.now(),url:window.location.href,...n?{isFinal:!0}:{},events:e}}createBatchId(e,t){return`${e}-${t}-${typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}`}getBatchSizeBytes(e){return new TextEncoder().encode(JSON.stringify(e)).byteLength}dropOldestPendingBatch(e){let t=this.pending.shift();t&&(this.pendingSizeBytes=Math.max(0,this.pendingSizeBytes-this.getBatchSizeBytes(t)),this.log(`${e}, dropping batch ${t.sequence}`))}enqueueBatch(e){let t=this.getBatchSizeBytes(e);if(t>this.maxQueueSizeBytes){this.log(`Replay batch ${e.sequence} is ${t}B, exceeding ${this.maxQueueSizeBytes}B queue limit; dropping`);return}for(;this.pending.length>0&&this.pendingSizeBytes+t>this.maxQueueSizeBytes;)this.dropOldestPendingBatch(`Pending queue size limit reached`);for(;this.pending.length>=this.maxPendingBatches;)this.dropOldestPendingBatch(`Pending batch limit reached`);this.pending.push(e),this.pendingSizeBytes+=t}async encodeBatch(e){let t=JSON.stringify(e);if(!this.shouldCompress||!this.compressionSupported)return{data:t,isCompressed:!1};try{let e=await this.compress(t);return this.log(`Compressed ${t.length}B -> ${e.byteLength}B (${Math.round(e.byteLength/t.length*100)}%)`),{data:e,isCompressed:!0}}catch{return this.log(`Compression failed, using uncompressed`),{data:t,isCompressed:!1}}}async flush(e,t,n){if(this.sending)return;let r=t?null:i(this.cookieless);if(r&&this.events.length>0)if(!this.hasReachedMinLength())this.scheduleMinLengthFlush();else{let e=this.createBatch(this.events.splice(0),r.prev,!0);this.enqueueBatch(e)}let a=t??this.sessionContext();if(this.events.length>0)if(!this.hasReachedMinLength())this.scheduleMinLengthFlush();else{let e=this.createBatch(this.events.splice(0),a,n);this.enqueueBatch(e)}if(this.pending.length!==0){this.sending=!0;try{for(;this.pending.length>0;){let t=this.pending[0];if(!t)break;let n=await this.encodeBatch(t);if(!await this.send(n.data,n.isCompressed,e)){this.log(`Failed to send replay batch ${t.sequence}, retrying`),this.scheduleRetry();break}this.dropOldestPendingBatch(`Sent replay batch`),e=!1}}finally{this.sending=!1}}}scheduleRetry(){this.retryTask||=setTimeout(()=>{this.retryTask=null,this.flush(!1)},1e3)}async compress(e){let t=new Blob([e]).stream().pipeThrough(new CompressionStream(`gzip`)),n=await new Response(t).arrayBuffer();return new Uint8Array(n)}send(e,t,n){return l({url:t?`${this.endpoint}?encoding=gzip`:this.endpoint,data:e,contentType:t?`application/octet-stream`:`application/json`,debug:!1,useBeacon:n,keepalive:n})??Promise.resolve(!1)}};export{p as n,v as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};export{t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{o as e,t}from"./session-manager-Cy63ptPF.js";const n=`faststats_anon_id`;function r(){try{return globalThis.localStorage}catch{return}}function i(t){return t??e()?``:a()}function a(){let e=r();if(!e)return``;try{let t=e.getItem(n);if(t)return t}catch{return``}let i=t();try{e.setItem(n,i)}catch{return``}return i}function o(e){if(e)return``;try{let e=r();if(!e)return``;e.removeItem(n)}catch{return``}return a()}async function s(e){let{url:t,data:n,contentType:r=`application/json`,headers:i={},debug:a=!1,debugPrefix:o=`[Analytics]`,useBeacon:s=!0,keepalive:c=!0}=e;if(s&&typeof globalThis.navigator?.sendBeacon==`function`)try{let e=n instanceof Blob?n:typeof Blob<`u`?new Blob([n],{type:r}):n;if(globalThis.navigator.sendBeacon(t,e))return a&&console.log(`${o} Sent via beacon`),!0}catch{}try{let e=await fetch(t,{method:`POST`,body:n,headers:{"Content-Type":r,...i},keepalive:c}),s=e.ok;if(a){let t=s?`${o} Sent via fetch`:`${o} Failed: ${e.status}`;console[s?`log`:`warn`](t)}return s}catch{return a&&console.warn(`${o} Failed to send`),!1}}export{i as n,o as r,s as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=`faststats_session_id`,t=`faststats_session_activity`,n=`faststats_session_start`,r=`session_id`,i=`session_timestamp`,a=`session_start`;let o=!1,s=``,c=null;const l=new Set;function u(e,t){try{return e?.getItem(t)??null}catch{return null}}function d(e,t,n){if(!e)return!1;try{return e.setItem(t,n),!0}catch{return!1}}function f(e,t){try{e?.removeItem(t)}catch{}}function p(){try{return globalThis.localStorage}catch{return}}function m(){try{return globalThis.sessionStorage}catch{return}}function h(e,t){for(let n of l)n(e,t)}function g(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function _(e){o=e,e&&(c=null)}function v(){return o}function y(e){s=e}function b(e){return`faststats_window_id_${e}`}function x(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:null}function S(){let o=m(),s=p(),c=u(o,r);if(!c||u(s,e)){c&&(f(o,r),f(o,i),f(o,a));return}let l=x(u(o,i)),h=x(u(o,a)),g=Date.now(),_=d(s,e,c);d(s,t,String(l??g)),d(s,n,String(h??l??g)),_&&(f(o,r),f(o,i),f(o,a))}function C(){S();let r=p(),i=u(r,e),a=x(u(r,t)),o=x(u(r,n));return!i||a===null?null:{sessionId:i,activity:a,sessionStart:o??a}}function w(r,i,a){let o=p(),s=d(o,e,r);d(o,t,i.toString()),d(o,n,a.toString()),s||(c={sessionId:r,activity:i,sessionStart:a})}function T(){let r=p();f(r,e),f(r,t),f(r,n)}function E(e,t,n){return n-e>=18e5?!0:n-t>=864e5}function D(e){return c||={sessionId:g(),sessionStart:e,activity:e},c}function O(e,t){let n=Date.now();if(e){let e=D(n);return t&&(e.activity=n),{sessionId:e.sessionId,sessionStart:e.sessionStart,rotated:!1,previous:null}}let r=C()??c;if(r&&!E(r.activity,r.sessionStart,n))return t&&w(r.sessionId,n,r.sessionStart),{sessionId:r.sessionId,sessionStart:r.sessionStart,rotated:!1,previous:null};let i=r===null?null:{sessionId:r.sessionId,sessionStart:r.sessionStart},a=g();return w(a,n,n),{sessionId:a,sessionStart:n,rotated:i!==null,previous:i}}function k(e,t){if(t??o)return O(!0,!1).sessionId;let n=b(e),r=m();if(!r)return O(!1,!1).sessionId;let i=u(r,n);if(i)return i;let a=g();return d(r,n,a),a}function A(e){f(m(),b(e))}function j(e,t){let n=t??o,r=O(n,!1),i=k(e,n),a={sessionId:r.sessionId,windowId:i,sessionStart:r.sessionStart};return r.rotated&&r.previous&&h({sessionId:r.previous.sessionId,windowId:i,sessionStart:r.previous.sessionStart},a),a}function M(e){return O(e??o,!0).sessionId}function N(e){return O(e??o,!1).sessionStart}function P(e){let t=e??o,n=O(t,!0);if(n.rotated&&n.previous){let e=s||`_default`,r={prev:{sessionId:n.previous.sessionId,windowId:k(e,t),sessionStart:n.previous.sessionStart},next:{sessionId:n.sessionId,windowId:k(e,t),sessionStart:n.sessionStart}};return h(r.prev,r.next),r}return null}function F(e){let t=e??o,n=Date.now();if(t){c&&(c.activity=n);return}let r=C()??c;r&&w(r.sessionId,n,r.sessionStart)}function I(e){let t=e??s??`_default`,n=Date.now(),r=null;if(o)c&&(r={sessionId:c.sessionId,windowId:c.sessionId,sessionStart:c.sessionStart}),c={sessionId:g(),sessionStart:n,activity:n};else{let e=C();e&&(r={sessionId:e.sessionId,windowId:k(t,!1),sessionStart:e.sessionStart}),T(),c=null}A(t);let i=j(t,o);return r&&r.sessionId!==i.sessionId&&h(r,i),i}function L(e){return l.add(e),()=>{l.delete(e)}}export{N as a,F as c,y as d,P as f,j as i,I as l,M as n,v as o,k as r,L as s,g as t,_ as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function e(e){return typeof e!=`number`||!Number.isFinite(e)?100:Math.max(0,Math.min(100,e))}export{e as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-MP-BAFHD.js";import{n as t,t as n}from"./api-urls-DaeYkG0_.js";import{n as r}from"./session-manager-Cy63ptPF.js";import{t as i}from"./types-CYzR5xtT.js";var a=e({default:()=>o}),o=class{endpoint;sampled;metrics=new Map;started=!1;url=``;constructor(e){this.options=e,this.endpoint=`${t(e.baseUrl)}${n.vitals}`,this.sampled=Math.random()*100<i(e.samplingPercentage)}get debug(){return this.options.debug??!1}log(...e){this.debug&&console.log(`[WebVitals]`,...e)}async start(){if(this.started||typeof window>`u`)return;this.started=!0,this.url=window.location.href,document.addEventListener(`visibilitychange`,this.onHidden,{passive:!0}),window.addEventListener(`pagehide`,this.onPageHide,{passive:!0});let e=this.options.attribution?await import(`web-vitals/attribution`):await import(`web-vitals`);this.started&&(e.onCLS(this.capture,{reportAllChanges:!0}),e.onINP(this.capture,{reportAllChanges:!0}),e.onLCP(this.capture,{reportAllChanges:!0}),e.onFCP(this.capture),e.onTTFB(this.capture),this.log(`Tracking started`))}stop(){!this.started||typeof window>`u`||(this.started=!1,this.removeListeners(),this.flush())}trackPageChange(e){if(!this.started||typeof window>`u`)return;let t=e??window.location.href;t!==this.url&&(this.flush(),this.url=t)}onHidden=()=>{document.visibilityState===`hidden`&&this.flush()};onPageHide=()=>{this.flush()};capture=e=>{if(!this.started||!this.sampled)return;let t=e.name,n=e.attribution;this.metrics.set(t,{metric:t,value:e.value,attributes:{id:e.id,rating:e.rating,delta:e.delta,navigationType:e.navigationType,...n??{}}})};async flush(){if(typeof window>`u`||typeof fetch!=`function`||!this.metrics.size)return;let e=Array.from(this.metrics.values()),t=this.url;this.metrics.clear();try{let n=new AbortController,i=window.setTimeout(()=>n.abort(),3e3),a=await fetch(this.endpoint,{method:`POST`,body:JSON.stringify({sessionId:r(),vitals:e,metadata:{url:t}}),headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.options.siteKey}`},keepalive:!0,signal:n.signal});if(clearTimeout(i),!a.ok)throw Error(`HTTP ${a.status}`)}catch(e){this.log(`Failed to send metrics`,e)}}removeListeners(){document.removeEventListener(`visibilitychange`,this.onHidden),window.removeEventListener(`pagehide`,this.onPageHide)}};export{a as n,o as t};
|
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
import { readdir, readFile, stat } from "node:fs/promises";
|
|
2
|
-
import { join, resolve } from "node:path";
|
|
3
|
-
import { gzipSync } from "node:zlib";
|
|
4
|
-
|
|
5
|
-
const distDir = resolve(process.cwd(), "dist");
|
|
6
|
-
|
|
7
|
-
const ENTRY_BUDGETS = {
|
|
8
|
-
"index.js": { raw: 18 * 1024, gzip: 7 * 1024 },
|
|
9
|
-
"feature-flags.js": { raw: 4 * 1024, gzip: 2 * 1024 },
|
|
10
|
-
"replay.js": { raw: 8 * 1024, gzip: 4 * 1024 },
|
|
11
|
-
"error.js": { raw: 5 * 1024, gzip: 3 * 1024 },
|
|
12
|
-
"web-vitals.js": { raw: 4 * 1024, gzip: 2 * 1024 },
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
const TOTAL_BUDGET = { raw: 40 * 1024, gzip: 16 * 1024 };
|
|
16
|
-
|
|
17
|
-
function formatBytes(bytes) {
|
|
18
|
-
return `${(bytes / 1024).toFixed(2)} KB`;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
async function listJs(dir) {
|
|
22
|
-
const entries = await readdir(dir, { withFileTypes: true });
|
|
23
|
-
const files = [];
|
|
24
|
-
for (const entry of entries) {
|
|
25
|
-
const full = join(dir, entry.name);
|
|
26
|
-
if (entry.isDirectory()) {
|
|
27
|
-
files.push(...(await listJs(full)));
|
|
28
|
-
} else if (entry.isFile() && entry.name.endsWith(".js")) {
|
|
29
|
-
files.push(full);
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
return files;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
const failures = [];
|
|
36
|
-
let totalRaw = 0;
|
|
37
|
-
let totalGzip = 0;
|
|
38
|
-
|
|
39
|
-
for (const [name, budget] of Object.entries(ENTRY_BUDGETS)) {
|
|
40
|
-
const path = join(distDir, name);
|
|
41
|
-
let info;
|
|
42
|
-
try {
|
|
43
|
-
info = await stat(path);
|
|
44
|
-
} catch {
|
|
45
|
-
failures.push(`Missing entry: ${name}`);
|
|
46
|
-
continue;
|
|
47
|
-
}
|
|
48
|
-
const buffer = await readFile(path);
|
|
49
|
-
const gzipped = gzipSync(buffer).byteLength;
|
|
50
|
-
|
|
51
|
-
const status = [];
|
|
52
|
-
if (info.size > budget.raw) {
|
|
53
|
-
status.push(`raw ${formatBytes(info.size)} > ${formatBytes(budget.raw)}`);
|
|
54
|
-
}
|
|
55
|
-
if (gzipped > budget.gzip) {
|
|
56
|
-
status.push(`gzip ${formatBytes(gzipped)} > ${formatBytes(budget.gzip)}`);
|
|
57
|
-
}
|
|
58
|
-
if (status.length > 0) {
|
|
59
|
-
failures.push(`${name}: ${status.join(", ")}`);
|
|
60
|
-
}
|
|
61
|
-
console.log(
|
|
62
|
-
`${name.padEnd(20)} raw ${formatBytes(info.size).padStart(10)} gzip ${formatBytes(gzipped).padStart(10)}`,
|
|
63
|
-
);
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
const allFiles = await listJs(distDir);
|
|
67
|
-
for (const file of allFiles) {
|
|
68
|
-
const buf = await readFile(file);
|
|
69
|
-
totalRaw += buf.byteLength;
|
|
70
|
-
totalGzip += gzipSync(buf).byteLength;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
console.log(
|
|
74
|
-
`${"total".padEnd(20)} raw ${formatBytes(totalRaw).padStart(10)} gzip ${formatBytes(totalGzip).padStart(10)}`,
|
|
75
|
-
);
|
|
76
|
-
|
|
77
|
-
if (totalRaw > TOTAL_BUDGET.raw) {
|
|
78
|
-
failures.push(
|
|
79
|
-
`total raw ${formatBytes(totalRaw)} > ${formatBytes(TOTAL_BUDGET.raw)}`,
|
|
80
|
-
);
|
|
81
|
-
}
|
|
82
|
-
if (totalGzip > TOTAL_BUDGET.gzip) {
|
|
83
|
-
failures.push(
|
|
84
|
-
`total gzip ${formatBytes(totalGzip)} > ${formatBytes(TOTAL_BUDGET.gzip)}`,
|
|
85
|
-
);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
if (failures.length > 0) {
|
|
89
|
-
console.error("\nBundle size check failed:");
|
|
90
|
-
for (const failure of failures) {
|
|
91
|
-
console.error(` - ${failure}`);
|
|
92
|
-
}
|
|
93
|
-
process.exit(1);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
console.log("\nBundle size check passed.");
|