@chrom-ar/collector 0.4.0 → 0.5.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/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0 (2026-11-23)
4
+
5
+ - Single-file builds for pages without a bundler: `dist/collector.esm.js`
6
+ and `dist/rum.esm.js` import nothing, so they work under any URL an
7
+ import map or a digested asset name gives them. Minified, with a
8
+ license line.
9
+ - A bare `init()` reads the DSN, environment and release from
10
+ `<meta name="collector-dsn">`, `collector-environment` and
11
+ `collector-release`, and the user from `collector-user` (a `setUser()`
12
+ call wins). Options passed to `init()` win over the tags.
13
+ - `rum()` without a `sampleRate` reads `collector-rum-sample-rate`, and
14
+ `<meta name="collector-route">` names the page load's page view
15
+ (`setRoute()` and the `route` option win over it).
16
+ - Turbo: on each `turbo:load`, the user and route tags are read again (a
17
+ missing user tag clears the user) and RUM counts the visit.
18
+ - **Can regroup issues:** on pages with an import map, frames from scoped
19
+ packages (`@scope/name`) and pins served from another origin are no
20
+ longer your code; with `<meta name="collector-in-app">`, only the
21
+ specifiers it lists are. Frames from `collector.esm.js` itself are never
22
+ your code. Errors whose grouping ran through those frames can open new
23
+ issues once.
24
+ - README: what a Content Security Policy needs (`connect-src` with the
25
+ DSN's origin, nothing else).
26
+ - README: Node servers use the new `@chrom-ar/collector-node`.
27
+ - README: source maps are uploaded with the `collector` CLI (now in Go);
28
+ the Vite plugin from `@chrom-ar/collector-cli` is gone. With Vite, set
29
+ the release with `define: { __COLLECTOR_RELEASE__ }`.
30
+
3
31
  ## 0.4.0 (2026-11-09)
4
32
 
5
33
  - Page speed (RUM), opt-in and in its own import:
package/README.md CHANGED
@@ -5,7 +5,7 @@ which groups them into issues, emails you when one is new or comes back,
5
5
  and shows you what broke and why.
6
6
 
7
7
  Works with any framework (React, Vue, Svelte, Angular, plain pages), has
8
- no dependencies and weighs about 6 KB gzipped.
8
+ no dependencies and weighs about 10 KB gzipped.
9
9
 
10
10
  ## Installation
11
11
 
@@ -41,6 +41,31 @@ Collector.init({ dsn: import.meta.env.VITE_COLLECTOR_DSN });
41
41
  `environment` and `release` are optional. Issues are counted per
42
42
  environment, and `release` tells you which deploy an error came from.
43
43
 
44
+ ### Without a bundler
45
+
46
+ For pages that load modules straight from an import map (or a plain
47
+ `<script type="module">`), the package ships one file each that imports
48
+ nothing: `dist/collector.esm.js` and `dist/rum.esm.js`. Copy them into
49
+ your assets (they keep their license line), pin them, and give the
50
+ settings in meta tags, so a bare `init()` needs no build step:
51
+
52
+ ```html
53
+ <meta name="collector-dsn" content="https://clt_…@app.clt.chrom.ar">
54
+ <meta name="collector-environment" content="production">
55
+ <meta name="collector-release" content="web@1.4.2">
56
+ <meta name="collector-user" content="u_42">
57
+ <script type="importmap">
58
+ { "imports": { "@chrom-ar/collector": "/assets/collector.esm.js" } }
59
+ </script>
60
+ <script type="module">
61
+ import * as Collector from "@chrom-ar/collector";
62
+ Collector.init();
63
+ </script>
64
+ ```
65
+
66
+ Options you pass to `init()` win over the tags. `collector-user` is
67
+ optional; a `setUser()` call wins over it, from then on.
68
+
44
69
  ### New domains
45
70
 
46
71
  The first time events arrive from a new domain, Collector keeps them and
@@ -50,6 +75,33 @@ browser console:
50
75
 
51
76
  > [collector] This site's domain (https://…) is blocked for this project in Collector (HTTP 403). Events won't be sent from this page.
52
77
 
78
+ ### Content Security Policy
79
+
80
+ If your site sends a Content Security Policy, add your DSN's origin (its
81
+ scheme, host and port) to `connect-src`, next to the ones you already
82
+ allow:
83
+
84
+ ```
85
+ Content-Security-Policy: connect-src 'self' https://app.clt.chrom.ar
86
+ ```
87
+
88
+ That's all it needs, with or without RUM:
89
+
90
+ - Events, heartbeats, page views and `Collector.test()` go out with
91
+ `fetch` or `navigator.sendBeacon`, which `connect-src` covers.
92
+ - Nothing for `script-src` beyond your own scripts: the package is bundled
93
+ with your code (or served from your assets, without a bundler), and it
94
+ doesn't load scripts or use `eval` or `new Function`.
95
+ - RUM's performance measurements and its `sessionStorage` entry aren't
96
+ covered by CSP.
97
+
98
+ If `connect-src` is missing it, the browser blocks the requests and logs
99
+ its own CSP error in the console; nothing reaches Collector.
100
+ `Collector.test()` (see [Checking your setup](#checking-your-setup))
101
+ then answers "couldn't reach Collector (…). Check the DSN's host, your
102
+ network, and your Content-Security-Policy's connect-src." CSP violation reports
103
+ (`report-uri`, `report-to`) go wherever your policy says, not to Collector.
104
+
53
105
  ### Framework notes
54
106
 
55
107
  - **Next.js, Nuxt, SvelteKit and other SSR frameworks:** importing the
@@ -65,6 +117,9 @@ browser console:
65
117
  ```
66
118
 
67
119
  - **Vue:** add `app.config.errorHandler = (error) => Collector.captureException(error);`
120
+ - **Turbo:** on each `turbo:load`, the SDK reads the `collector-user` and
121
+ `collector-route` tags again (a missing `collector-user` clears the
122
+ user), and RUM counts the visit. Render the tags in your layout.
68
123
 
69
124
  ## Checking your setup
70
125
 
@@ -180,7 +235,9 @@ Collector.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
180
235
  ```
181
236
 
182
237
  - **Sampling:** `sampleRate` is the share of browser tabs measured,
183
- decided once per tab. A measured tab sends all its page views.
238
+ decided once per tab. A measured tab sends all its page views. Without
239
+ it, `rum()` reads `<meta name="collector-rum-sample-rate" content="0.1">`;
240
+ with neither, nothing is measured.
184
241
  - **What's measured:** for page loads, LCP, INP, CLS, TTFB and FCP; for
185
242
  in-app navigations to a new path (pushState, LiveView; a new query
186
243
  string alone, like a filter or a search box, stays the same page view),
@@ -206,9 +263,11 @@ Collector.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
206
263
  Collector.setRoute("/orders/:id");
207
264
  ```
208
265
 
209
- or pass `route: (location) => …` to `rum()`. Apps that route in the
210
- `#hash` need this: fragments are never sent, so every page would
211
- otherwise be `/`.
266
+ or pass `route: (location) => …` to `rum()`, or render
267
+ `<meta name="collector-route" content="/orders/:id">`: it names the
268
+ page load, and with Turbo each visit. `setRoute()` wins over `route`,
269
+ and `route` over the tag. Apps that route in the `#hash` need one of
270
+ these: fragments are never sent, so every page would otherwise be `/`.
212
271
  - **Editing or dropping page views:** `rum({ sampleRate, beforeSendPageview(pv) { … return pv; } })`;
213
272
  return `null` to drop one.
214
273
 
@@ -227,34 +286,45 @@ say so:
227
286
  Collector.init({ dsn: "…", inAppUrls: ["https://cdn.example.com/app/"] });
228
287
  ```
229
288
 
289
+ On a page with an import map, a module pinned to a bare specifier is
290
+ judged by its specifier: scoped packages (`@scope/name`) and pins served
291
+ from another origin are dependencies, other pins stay your code. To say
292
+ exactly which pins are yours, list them (a trailing `/` covers every
293
+ specifier under it); every other pin is then a dependency:
294
+
295
+ ```html
296
+ <meta name="collector-in-app" content="application controllers/">
297
+ ```
298
+
299
+ `inAppUrls` wins over both. Frames from `collector.esm.js` itself are
300
+ never your code.
301
+
230
302
  ## Source maps
231
303
 
232
304
  Upload your build's source maps and Collector shows your original files,
233
- lines and function names, and groups errors by them. With Vite, add the
234
- plugin from [`@chrom-ar/collector-cli`](https://www.npmjs.com/package/@chrom-ar/collector-cli):
235
-
236
- ```ts
237
- // vite.config.ts
238
- import collector from "@chrom-ar/collector-cli/vite";
305
+ lines and function names, and groups errors by them. Upload them with the
306
+ [`collector` CLI](https://github.com/chrom-ar/collector-cli) before you
307
+ deploy, with `COLLECTOR_UPLOAD_TOKEN` (from your project's settings) and
308
+ `COLLECTOR_DSN` set in your CI:
239
309
 
240
- export default defineConfig({ plugins: [collector()] });
310
+ ```sh
311
+ collector upload ./dist --release "$GIT_SHA"
241
312
  ```
242
313
 
243
- Set `COLLECTOR_UPLOAD_TOKEN` (from your project's settings) and
244
- `COLLECTOR_DSN` in your CI. The plugin uploads the maps at the end of
245
- `vite build`, removes them from the output, and injects the release, so you
246
- don't need to pass `release` to `init()`.
247
-
248
- With another bundler, upload with the CLI before you deploy, and make the
249
- release match:
314
+ Make the app report the same release: pass it to `init({ release })`, or
315
+ define the `__COLLECTOR_RELEASE__` constant at build time. With Vite, build
316
+ hidden source maps so the bundle doesn't point to them, and delete the maps
317
+ before you deploy (`collector upload --delete` does it):
250
318
 
251
- ```sh
252
- npx @chrom-ar/collector-cli upload ./dist --release "$GIT_SHA"
319
+ ```ts
320
+ // vite.config.ts
321
+ export default defineConfig({
322
+ build: { sourcemap: "hidden" },
323
+ define: { __COLLECTOR_RELEASE__: JSON.stringify(process.env.GIT_SHA) },
324
+ });
253
325
  ```
254
326
 
255
- Pass the same value to `init({ release })`, or define the
256
- `__COLLECTOR_RELEASE__` constant at build time (e.g. webpack's
257
- `new DefinePlugin({ __COLLECTOR_RELEASE__: JSON.stringify(sha) })`).
327
+ With webpack: `new DefinePlugin({ __COLLECTOR_RELEASE__: JSON.stringify(sha) })`.
258
328
 
259
329
  ## What it won't do (yet)
260
330
 
@@ -265,8 +335,9 @@ Pass the same value to `init({ release })`, or define the
265
335
  (`Cart.checkout` in Chrome and `checkout` in Firefox both become
266
336
  `checkout`), but Safari sometimes leaves frames out, so the same error
267
337
  can occasionally group separately per browser.
268
- - **Browsers only.** For servers, use a server SDK
269
- ([Elixir](https://hex.pm/packages/collector)).
338
+ - **Browsers only.** For servers, use a server SDK: Node
339
+ ([`@chrom-ar/collector-node`](https://www.npmjs.com/package/@chrom-ar/collector-node),
340
+ for Express and Next.js) or [Elixir](https://hex.pm/packages/collector).
270
341
 
271
342
  It never throws into your app, never blocks it, and keeps quiet in the
272
343
  console unless something's misconfigured (or you set `debug: true`).
@@ -1,3 +1,10 @@
1
+ // src/meta.ts
2
+ function readMeta(name) {
3
+ if (typeof document === "undefined") return void 0;
4
+ const content = document.querySelector(`meta[name="${name}"]`)?.content.trim();
5
+ return content === void 0 || content === "" ? void 0 : content;
6
+ }
7
+
1
8
  // src/util.ts
2
9
  function uuid4() {
3
10
  if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
@@ -53,4 +60,4 @@ function rumUrl(base, url) {
53
60
  }
54
61
  }
55
62
 
56
- export { rumUrl, safeStringify, stripUrl, truncate, uuid4 };
63
+ export { readMeta, rumUrl, safeStringify, stripUrl, truncate, uuid4 };
@@ -0,0 +1,7 @@
1
+ /*! @chrom-ar/collector v0.5.0 | MIT */
2
+ function ee(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let t=crypto.getRandomValues(new Uint8Array(16));t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let e=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return `${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function b(t,e){if(t.length<=e)return t;let n=t.charCodeAt(e-1);return t.slice(0,n>=55296&&n<=56319?e-1:e)}function W(t,e=8192){return b(Ae(t),e)}function Ae(t){if(typeof t=="string")return t;if(t===void 0||typeof t=="function"||typeof t=="symbol"||typeof t=="bigint")return String(t);let e=new WeakSet;try{return JSON.stringify(t,(n,r)=>{if(typeof r=="bigint")return r.toString();if(typeof r=="object"&&r!==null){if(e.has(r))return "[Circular]";e.add(r);}return r})}catch{try{return String(t)}catch{return "[unserializable]"}}}function f(t){let e=t.search(/[?#]/);return e===-1?t:t.slice(0,e)}var Ne=500;function te(t,e){try{let n=new URL(e,t);return n.protocol!=="http:"&&n.protocol!=="https:"?void 0:(n.origin+n.pathname).slice(0,Ne)}catch{return}}var ne;function re(t){ne=f(t);}var oe=()=>ne;function ie(t){let e;try{e=new URL(t);}catch{return null}if(e.protocol!=="https:"&&e.protocol!=="http:"||e.username==="")return null;let n=e.origin+e.pathname.replace(/\/+$/,""),r=e.username;return {url:`${n}/api/events?key=${r}`,heartbeatUrl:`${n}/api/heartbeats?key=${r}`,pageviewsUrl:`${n}/api/pageviews?key=${r}`,base:n,key:r}}var Me=250,Ue=/^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/,Ie=/^(.*?)@(.*):(\d+):(\d+)$/,$e=/\((\S+?):(\d+):(\d+)\)/,Fe=/^(.*?) line (\d+) > (?:eval|Function)/,Be=new Set(["global code","module code","eval code"]);function se(t){let e=[];for(let n of t.split(`
3
+ `)){let r=Pe(n)??De(n);r&&e.push(r);}return e}function Pe(t){let e=Ue.exec(t);if(e?.[2]===void 0)return;let n=e[2],r=Number(e[3]),o=Number(e[4]);if(n.startsWith("eval at ")){let i=$e.exec(n);if(i?.[1]===void 0)return;n=i[1],r=Number(i[2]),o=Number(i[3]);}return {function:K(e[1]),url:n,line:r,column:o}}function De(t){let e=Ie.exec(t);if(e?.[2]===void 0||e[2]==="")return;let n=e[1],r=/^([^*]*)\*(.*)$/.exec(n??"");if(r){if(r[1]!=="async")return;n=r[2];}let o=Fe.exec(e[2]);return o?.[1]!==void 0&&o[1]!==""?{function:K(n),url:o[1],line:Number(o[2]),column:void 0}:{function:K(n),url:e[2],line:Number(e[3]),column:Number(e[4])}}function K(t){if(t===void 0||t===""||Be.has(t))return;let e=t.replace(/^async\*/,"").replace(/^(?:async|new) /,"").replace(/ \[as [^\]]*\]$/,"").replace(/[/<]+$/,""),n=e.slice(Math.max(e.lastIndexOf("."),e.lastIndexOf("/"))+1);return n!==""&&n!=="<anonymous>"?n:void 0}function X(t){return /^(?:chrome|moz|safari|safari-web)-extension:\/\//.test(t)}var je=[/\/node_modules\//,/\/\.vite\/deps\//,/\/vendors?(?:\/|[-.~][^/]*$)/,/chunk-vendors/,/vendors~/,/\/@vite\//,/\/@react-refresh/,/\/_next\/static\/chunks\/(?:framework|main|webpack)[-.]/],qe=/[-.~]([A-Za-z0-9_]{8,}|[A-Za-z0-9_-]{8})(?=\.)/g;function He(t){return /\d/.test(t)?true:t.length!==8?false:/[_-]/.test(t)||/[A-Z]/.test(t)&&/[a-z]/.test(t)&&!/[a-z]{3}/.test(t)}function We(t){let e=f(t),n=e.lastIndexOf("/")+1,r=e.slice(n).replace(qe,(o,i)=>He(i)?"":o);return e.slice(0,n)+r}function ae(t,e){let n=[];for(let r of t)if(r.function?.startsWith("__collector")!==true){if(n.length===Me)break;n.push(Ke(r,e));}return n}function Ke(t,{origin:e,inAppUrls:n,classify:r,sdkFile:o}){let i;try{i=new URL(t.url,e);}catch{i=void 0;}let s=t.url.startsWith("webpack-internal://"),u=i?.origin===e||s,c=f(t.url);i&&!s&&(c=u?i.pathname:f(i.href));let a=d();function d(){if(o!==void 0&&i!==void 0&&f(i.href)===o)return false;if(n)return n.some(h=>typeof h=="string"?t.url.includes(h):h.test(t.url));let g=i===void 0?void 0:r?.(i.href);return g!==void 0?g==="app":u&&!X(t.url)&&!je.some(h=>h.test(c))}let l={module:We(c),function:t.function??"?",file:c,in_app:a};return t.line!==void 0&&(l.line=t.line),t.column!==void 0&&(l.column=t.column),l}var G=8192,Xe=new Set(["fatal","error","warning","info"]),Ge={debug:"info",log:"info",warn:"warning",critical:"fatal"};function Ve(t){return typeof t!="string"?"error":Xe.has(t)?t:Ge[t]??"error"}var x="@chrom-ar/collector";function Qe(t){if(t instanceof Error)return true;if(typeof t!="object"||t===null)return false;let e=t;return typeof e.message=="string"&&(typeof e.name=="string"||typeof e.stack=="string")}function ze(t){if(typeof t.name=="string"&&t.name!=="")return t.name;let e=t.constructor?.name;return typeof e=="string"&&e!==""&&e!=="Object"?e:"Error"}function V(t,e,n,r="manual"){let o=ce(e,n);if(Qe(t)){let i=typeof t.stack=="string"?ae(se(t.stack),{origin:e.origin,inAppUrls:e.options.inAppUrls,classify:e.classify,sdkFile:oe()}):[];o.exception={type:ze(t),message:b(String(t.message),G)},i.length>0&&(o.exception.frames=i);}else o.exception={type:r==="onunhandledrejection"?"UnhandledRejection":"NonError",message:W(t,G)};return o}function ue(t,e,n){let r=ce(e,n);return r.message=W(t,G),r}function Je(){return typeof __COLLECTOR_RELEASE__=="string"?__COLLECTOR_RELEASE__:void 0}function k(t){let e=t.release??Je();return e===""?void 0:e}function T(t){return typeof t.environment=="string"&&t.environment!==""?t.environment:void 0}function ce({options:t,scope:e,href:n,userAgent:r,session:o},i={}){let s={v:1,uuid:ee(),timestamp:new Date().toISOString(),platform:"javascript",level:Ve(i.level),request:{url:t.stripQuery===false?n:f(n),headers:{"user-agent":r}},sdk:{name:x,version:"0.5.0"}},u=T(t);u!==void 0&&(s.environment=u);let c=k(t);c!==void 0&&(s.release=c),o!==void 0&&(s.session=o),i.fingerprint&&i.fingerprint.length>0&&(s.fingerprint=i.fingerprint.map(String));let a=i.user?{id:String(i.user.id)}:e.user;a&&(s.user=a);let d={...e.tags,...i.tags};Object.keys(d).length>0&&(s.tags=d);let l=e.getBreadcrumbs();return l.length>0&&(s.breadcrumbs=l),s}var de=["ResizeObserver loop limit exceeded","ResizeObserver loop completed with undelivered notifications",/^(?:Error: )?Script error\.?$/];function le(t){let{exception:e}=t;return e?e.message!==void 0&&e.message!==""?`${e.type}: ${e.message}`:e.type:t.message??""}function fe(t,e){let n=t.exception?.frames;if(n!==void 0&&n.length>0&&n.every(o=>X(o.file)))return true;let r=le(t);return e.some(o=>typeof o=="string"?r.includes(o):o.test(r))}var A=class{constructor(e=1e3){this.windowMs=e;this.lastAt=0;}isDuplicate(e,n){let r=(e.exception?.frames??[]).slice(0,5).map(s=>`${s.file}:${String(s.line)}:${String(s.column)}`),o=`${le(e)}
4
+ ${r.join(`
5
+ `)}`,i=o===this.last&&n-this.lastAt<=this.windowMs;return this.last=o,this.lastAt=n,i}},N=class{constructor(e=30,n=1e4){this.max=e;this.windowMs=n;this.times=[];}take(e){return this.times=this.times.filter(n=>e-n<this.windowMs),this.times.length>=this.max?false:(this.times.push(e),true)}};function pe(t,e,n){let r=i=>{try{if(typeof i.target?.nodeType=="number")return;let s=i;e(s.error??Ze(s),"onerror");}catch{}},o=i=>{try{e(i.reason,"onunhandledrejection");}catch{}};return n.onerror&&t.addEventListener("error",r),n.onunhandledrejection&&t.addEventListener("unhandledrejection",o),()=>{t.removeEventListener("error",r),t.removeEventListener("unhandledrejection",o);}}var Ye=/^(?:Uncaught |uncaught exception: )?(null|undefined)$/;function Ze(t){let e=Ye.exec(t.message),n=new Error(e?.[1]??(t.message!==""?t.message:"Unknown error"));return e&&(n.name="NonError"),n.stack=typeof t.filename=="string"&&t.filename!==""?`${n.name}: ${n.message}
6
+ at ? (${t.filename}:${String(t.lineno)}:${String(t.colno)})`:"",n}function E(t){if(typeof document>"u")return;let e=document.querySelector(`meta[name="${t}"]`)?.content.trim();return e===void 0||e===""?void 0:e}var et=t=>!/^(?:\.{0,2}\/|[a-z][a-z\d+.-]*:)/i.test(t);function tt(t){let n=t.querySelector('script[type="importmap"]')?.textContent;if(n===void 0||n==="")return;let r;try{r=JSON.parse(n);}catch{return}let o=typeof r=="object"&&r!==null&&"imports"in r?r.imports:void 0;if(typeof o!="object"||o===null)return;let i=[];for(let[s,u]of Object.entries(o))if(!(typeof u!="string"||!et(s)))try{i.push({specifier:s,url:f(new URL(u,t.baseURI).href),prefix:s.endsWith("/")});}catch{}return i.sort((s,u)=>s.prefix===u.prefix?u.url.length-s.url.length:Number(s.prefix)-Number(u.prefix))}var nt=(t,e)=>t.some(n=>n===e||n.endsWith("/")&&e.startsWith(n));function me(t,e){let n=tt(t);if(!n||n.length===0)return;let r=E("collector-in-app")?.split(/[\s,]+/).filter(o=>o!=="");return o=>{let i=f(o),s=n.find(c=>c.prefix?i.startsWith(c.url):i===c.url);if(!s)return;let u=s.prefix?s.specifier+i.slice(s.url.length):s.specifier;return r?nt(r,u)?"app":"dependency":u.startsWith("@")||!s.url.startsWith(`${e}/`)?"dependency":void 0}}var ge=5e3,rt="collector:heartbeat:",he=new Set;function ye(t){let e,n=()=>{it(t);},r=setTimeout(()=>{"requestIdleCallback"in globalThis?e=requestIdleCallback(n,{timeout:ge}):n();},ge);return ()=>{clearTimeout(r),e!==void 0&&cancelIdleCallback(e);}}function ot(t){try{return localStorage.getItem(t)}catch{return null}}async function it({url:t,key:e,fetch:n,options:r,logger:o}){let i=k(r),s=T(r),u=rt+e,c=JSON.stringify([new Date().toISOString().slice(0,10),i??"",s??""]);if(ot(u)===c||he.has(u+c))return;let a;try{let d=JSON.stringify({v:1,sdk:{name:x,version:"0.5.0"},environment:s,release:i});({status:a}=await n(t,{method:"POST",body:d,headers:{"Content-Type":"text/plain;charset=UTF-8"},keepalive:!0,credentials:"omit"}));}catch(d){o.debug("heartbeat not sent",d);return}if(!(a===429||a>=500))try{localStorage.setItem(u,c);}catch{he.add(u+c);}}var M=10,st=100;function U(t,e=false){if(typeof t=="string")return e?JSON.stringify(b(t,st)):t;if(t===null||typeof t!="object")return typeof t=="function"?`[Function ${t.name!==""?t.name:"anonymous"}]`:String(t);let n=t;if(t instanceof Error||typeof n.message=="string"&&typeof n.name=="string")return `${String(n.name)}: ${String(n.message)}`;if(typeof n.nodeType=="number")return typeof n.tagName=="string"?`<${n.tagName.toLowerCase()}>`:"[Node]";if(e)return Array.isArray(t)?`[Array(${String(t.length)})]`:"{\u2026}";if(Array.isArray(t))return `[${t.slice(0,M).map(o=>U(o,true)).join(", ")}${t.length>M?", \u2026":""}]`;try{let r=Object.keys(t);return `{${r.slice(0,M).map(i=>`${i}: ${U(t[i],!0)}`).join(", ")}${r.length>M?", \u2026":""}}`}catch{return "{\u2026}"}}var ve="__collector_original__";function w(t,e,n){let r=t[e];if(typeof r!="function"||r[ve]!==void 0)return ()=>true;let o=n(r);return Object.defineProperty(o,ve,{value:r}),t[e]=o,()=>t[e]!==o?false:(t[e]=r,true)}function m(t){try{t();}catch{}}function R(t,e,n){let r=e;try{let o=new URL(e,t.location.href);o.username="",o.password="",r=o.origin===t.location.origin?o.pathname+o.search+o.hash:o.href;}catch{}return n?f(r):r}function I(t,e,n,r){let o=t.onRequest?te(e.location.href,r):void 0;if(o===void 0)return ()=>{};let i=performance.now(),s=t.onRequestStart?.();return u=>{t.onRequest?.({method:n.toUpperCase(),url:o,status:u??0,start:i,end:performance.now()},s);}}function $(t,e){try{return new URL(e,t.location.href).href}catch{return e}}function F(t){return t===void 0||t>=500?"error":t>=400?"warning":"info"}function B(t,e,n){return `${t.toUpperCase()} ${e} \u2192 ${n===void 0?"failed":String(n)}`}var be={error:"error",warn:"warning",log:"info",info:"info"};function we(t,e,n){let r=t.console,o=Object.keys(be).map(i=>w(r,i,s=>function(...c){m(()=>{e({category:"console",level:be[i],message:b(c.map(a=>U(a)).join(" "),500)});}),s.apply(this,c);}));return ()=>o.map(i=>i()).every(Boolean)}var at=3;function ut(t){let e=[],n=t;for(;n&&e.length<at&&n.tagName!=="BODY"&&n.tagName!=="HTML";){let r=n.tagName.toLowerCase();n.id!==""&&(r+=`#${n.id}`);for(let o of Array.from(n.classList))r+=`.${o}`;e.unshift(r),n=n.parentElement;}return e.join(" > ")}function Ee(t,e,n){let r=o=>{m(()=>{let i=o.target;if(i?.nodeType!==1)return;let s=ut(i);s!==""&&e({category:"ui.click",level:"info",message:s});});};return t.document.addEventListener("click",r,true),()=>(t.document.removeEventListener("click",r,true),true)}function ct(t,e){let n=typeof Request<"u"&&t instanceof Request,r;return n?r=t.url:t instanceof URL?r=t.href:r=String(t),{method:e?.method??(n?t.method:"GET"),url:r}}function Se(t,e,n){return w(t,"fetch",r=>async function(i,s){let u=r.apply(this,arguments),c=a=>{};return m(()=>{let{method:a,url:d}=ct(i,s);if(n.skipUrl($(t,d)))return;let l=R(t,d,n.stripQuery),g=I(n,t,a,d);c=h=>{m(()=>{g(h),e({category:"fetch",level:F(h),message:B(a,l,h)});});};}),u.then(a=>(c(a.status),a),a=>{throw c(void 0),a})})}function Re(t,e,n){let r=()=>{let d=R(t,t.location.href,n.stripQuery),{hash:l}=t.location;return !n.stripQuery||!/^#!?\//.test(l)?d:`${d}#${f(l.slice(1))}`},o=r(),i=()=>{m(()=>{let d=r();d!==o&&(e({category:"navigation",level:"info",message:`${o} \u2192 ${d}`}),o=d);});},s=d=>w(t.history,d,l=>function(...h){l.apply(this,h),i(),u();}),u=()=>{m(()=>{n.onNavigate?.();});},c=()=>{i(),u();},a=[s("pushState"),s("replaceState")];return t.addEventListener("popstate",c),t.addEventListener("hashchange",i),()=>a.map(d=>d()).every(Boolean)?(t.removeEventListener("popstate",c),t.removeEventListener("hashchange",i),true):false}function xe(t,e,n){let r=t.XMLHttpRequest;if(!r)return ()=>true;let o=r.prototype,i=new WeakMap,s=w(o,"open",c=>function(...d){m(()=>{let[l,g]=d;i.set(this,{method:String(l),url:g instanceof URL?g.href:String(g)});}),c.apply(this,d);}),u=w(o,"send",c=>function(d){m(()=>{let l=i.get(this);if(!l||n.skipUrl($(t,l.url)))return;let g=R(t,l.url,n.stripQuery),h=I(n,t,l.method,l.url);this.addEventListener("loadend",()=>{m(()=>{let H=this.status!==0?this.status:void 0;h(H),e({category:"xhr",level:F(H),message:B(l.method,g,H)});});},{once:!0});}),c.call(this,d);});return ()=>[s(),u()].every(Boolean)}function ke(t){let e=new Set,{debug:n,info:r,warn:o}=console;return {debug(...i){t()&&n.call(console,"[collector]",...i);},warnOnce(i){e.has(i)||(e.add(i),o.call(console,`[collector] ${i}`));},info(i){r.call(console,`[collector] ${i}`);},warn(i){o.call(console,`[collector] ${i}`);}}}var dt=500,S=class{constructor(){this.tags={};this.breadcrumbs=[];}setUser(e){this.user=e?{id:String(e.id)}:void 0;}setTag(e,n){this.tags[e]=String(n);}setTags(e){for(let[n,r]of Object.entries(e))this.setTag(n,r);}addBreadcrumb(e,n){this.breadcrumbs.push({...e,timestamp:e.timestamp??new Date().toISOString(),message:b(String(e.message),dt)}),this.breadcrumbs.length>n&&this.breadcrumbs.splice(0,this.breadcrumbs.length-n);}getBreadcrumbs(){return this.breadcrumbs.map(e=>({...e}))}clear(){this.user=void 0,this.tags={},this.breadcrumbs=[];}};function _(t,e){let{onAnswer:n}=t;t.onAnswer=void 0,n?.(e);}var Q=1e3,lt=6e4,ft=8,pt=60,Te=6e4,z=1e6,mt=50,gt=new TextEncoder,C=t=>gt.encode(t).length,P=class{constructor(e){this.deps=e;this.disabled=false;this.queue=[];this.inFlight=false;this.paused=false;this.backoff=Q;this.inFlightKeepaliveBytes=0;this.idleWaiters=[];this.maxQueue=e.maxQueue??30;}send(e,n){if(!this.disabled){if(this.queue.length>=this.maxQueue){let r=this.queue.shift();r&&_(r,{error:new Error("dropped: too many events queued")}),this.deps.logger.debug("queue full, dropped the oldest event");}this.queue.push({event:e,attempts:0,...n?{onAnswer:n}:{}}),this.dispatch();}}async flush(e=2e3){return this.isIdle()?Promise.resolve(true):new Promise(n=>{let r=setTimeout(()=>{this.idleWaiters=this.idleWaiters.filter(i=>i!==o),n(false);},e),o=()=>{clearTimeout(r),n(true);};this.idleWaiters.push(o);})}sendQueuedNow(){if(this.disabled||this.paused)return;let e=Te-this.inFlightKeepaliveBytes;for(let{event:n}of this.queue.splice(0)){let r=_e(n);if(r===void 0)continue;let o=C(r),i=o<=e;i&&(e-=o);try{this.deps.fetch(this.deps.url,{method:"POST",body:r,headers:{"Content-Type":"text/plain;charset=UTF-8"},keepalive:i,credentials:"omit"}).catch(()=>{});}catch{}}this.notifyIfIdle();}isIdle(){return !this.inFlight&&(this.queue.length===0||this.disabled)}dispatch(){let e=this.inFlight||this.paused||this.disabled?void 0:this.queue.shift();if(!e){this.notifyIfIdle();return}let n=_e(e.event);if(n===void 0){this.deps.logger.debug("dropped an event that is over 1 MB or not JSON-encodable",e.event.uuid),_(e,{error:new Error("dropped: over 1 MB or not JSON-encodable")}),this.dispatch();return}this.inFlight=true;let r=C(n),o=r<=Te;this.inFlightKeepaliveBytes=o?r:0;let i;try{i=this.deps.fetch(this.deps.url,{method:"POST",body:n,headers:{"Content-Type":"text/plain;charset=UTF-8"},keepalive:o,credentials:"omit"});}catch(s){i=Promise.reject(s instanceof Error?s:new Error(String(s)));}i.then(s=>{this.handle(e,s);},s=>{this.retry(e,s);});}handle(e,n){this.inFlight=false,this.inFlightKeepaliveBytes=0;let{status:r}=n;if(_(e,{status:r}),r>=200&&r<300)this.backoff=Q;else if(r===429)this.backoff=Q,this.pause(ht(n.headers.get("Retry-After"))*1e3);else if(r===401||r===403)this.disable(r);else if(r>=500){this.retry(e,`HTTP ${String(r)}`);return}else {let{logger:o}=this.deps;n.text().then(i=>{o.debug(`Collector rejected an event (HTTP ${String(r)})`,e.event.uuid,i);},()=>{o.debug(`Collector rejected an event (HTTP ${String(r)})`,e.event.uuid);});}this.dispatch();}retry(e,n){_(e,{error:n}),this.inFlight=false,this.inFlightKeepaliveBytes=0,e.attempts+=1,e.attempts>=ft?this.deps.logger.debug(`gave up on an event after ${String(e.attempts)} tries`,n):(this.deps.logger.debug("sending failed, will retry",n),this.queue.unshift(e));let r=this.backoff;this.backoff=Math.min(this.backoff*2,lt),this.pause(r);}pause(e){this.paused=true,setTimeout(()=>{this.paused=false,this.dispatch();},e);}disable(e){this.disabled=true;for(let r of this.queue.splice(0))_(r,{error:new Error(`dropped: Collector rejected this DSN (HTTP ${String(e)})`)});this.deps.onDisable?.();let n=this.deps.origin??"unknown origin";this.deps.logger.warnOnce(e===401?"Collector rejected the key (HTTP 401): check the DSN on your project's setup page. Nothing more will be sent from this page.":`This site's domain (${n}) is blocked for this project in Collector (HTTP 403). Events won't be sent from this page. A project admin can unblock it in the project's settings.`);}notifyIfIdle(){if(!this.isIdle())return;let e=this.idleWaiters;this.idleWaiters=[];for(let n of e)n();}};function ht(t){let e=Number.parseInt(t??"",10);return e>=0?e:pt}function _e(t){try{return yt(t)}catch{return}}function yt(t){let e=JSON.stringify(t);if(C(e)<=z)return e;let n={...t};if(delete n.breadcrumbs,e=JSON.stringify(n),C(e)<=z||n.exception?.frames&&(n.exception={...n.exception,frames:n.exception.frames.slice(0,mt)},e=JSON.stringify(n),C(e)<=z))return e}var vt={console:we,dom:Ee,fetch:Se,xhr:xe,history:Re},bt=50,Ce=1e4;function wt(t){if("error"in t)return `couldn't reach Collector (${t.error instanceof Error?t.error.message:String(t.error)}). Check the DSN's host, your network, and your Content-Security-Policy's connect-src.`;let{status:e}=t;if(!(e>=200&&e<300))return e===401?"Collector rejected the key (HTTP 401). Check the DSN on your project's setup page.":e===403?"this site's domain is blocked for the project (HTTP 403). A project admin can unblock it in the project's settings.":e===429?"Collector asked to slow down (HTTP 429). Try again in a minute.":e>=500?`Collector had an error (HTTP ${String(e)}). The event will be retried.`:`Collector rejected the event (HTTP ${String(e)}).`}var v,D=new Map,Et={skipUrl:t=>v?.isOwnUrl(t)??false,get stripQuery(){return v?.options.stripQuery!==false},onRequestStart:()=>v?.rum?.requestStart(),onRequest:(t,e)=>{v?.rum?.request(t,e);},onNavigate:()=>{v?.rum?.navigate();}},St=new Set(["fetch","xhr","history"]),Oe=new Set,Rt=t=>e=>{v&&v.options.breadcrumbs?.[t]!==false&&v.addBreadcrumb(e);};function xt(t){return t.__collector_original__??t}var j=class{constructor(e,n,r=new S){this.options=e;this.win=n;this.scope=r;this.cleanups=[];this.deduper=new A;this.rateGuard=new N;this.closed=false;if(this.logger=ke(()=>e.debug===true),this.ignore=[...de,...e.ignoreErrors??[]],e.enabled===false){this.logger.debug("disabled (enabled: false): nothing will be sent"),this.inactive="the SDK is off (enabled: false).";return}if(typeof e.dsn!="string"||e.dsn===""){this.logger.debug("no DSN given: nothing will be sent"),this.inactive="no DSN given to init().";return}let o=ie(e.dsn);if(!o){this.logger.debug("invalid DSN: nothing will be sent",e.dsn),this.inactive="invalid DSN. Copy it from your project's setup page.";return}this.endpointBase=o.base;let i=xt(n.fetch).bind(n),{url:s}=o;this.transport=new P({url:s,fetch:i,logger:this.logger,origin:n.location.origin,onDisable:()=>Oe.add(s)}),Oe.has(s)?(this.transport.disabled=true,this.logger.debug("Collector already rejected this DSN on this page: nothing will be sent")):e.heartbeat!==false&&this.cleanups.push(ye({url:o.heartbeatUrl,key:o.key,fetch:i,options:e,logger:this.logger}));let u=e.autoCapture;if(u!==false&&this.cleanups.push(pe(n,(a,d)=>this.captureException(a,void 0,d),{onerror:u?.onerror!==false,onunhandledrejection:u?.onunhandledrejection!==false})),e.rum&&!this.transport.disabled)try{this.rum=e.rum.start({win:n,url:o.pageviewsUrl,fetch:i,logger:this.logger,options:e,sdk:{name:x,version:"0.5.0"},environment:T(e),release:k(e)});}catch(a){this.logger.debug("RUM didn't start",a);}v=this;for(let[a,d]of Object.entries(vt))if(!(!(e.breadcrumbs?.[a]!==false||this.rum!==void 0&&St.has(a))||D.has(a)))try{D.set(a,d(n,Rt(a),Et));}catch(g){this.logger.debug(`couldn't record ${a} breadcrumbs`,g);}let c=()=>{this.transport?.sendQueuedNow();};n.addEventListener("pagehide",c),this.cleanups.push(()=>{n.removeEventListener("pagehide",c);});}captureException(e,n,r="manual"){return this.capture(()=>V(e,this.env(),n,r))}captureMessage(e,n){let r=typeof n=="string"?{level:n}:n;return this.capture(()=>ue(e,this.env(),r))}async test(){let e=i=>(this.logger.warn(`Test event not sent: ${i}`),{ok:false,reason:i}),{transport:n}=this;if(this.closed)return Promise.resolve(e("the SDK was closed."));if(!n)return Promise.resolve(e(this.inactive??"the SDK isn't sending."));if(n.disabled)return Promise.resolve(e("Collector already rejected this DSN on this page (HTTP 401/403)."));let r;try{let i=new Error("Test event from Collector.test(). If you can see it in Collector, your setup works.");throw i.name="CollectorTest",i}catch(i){r=V(i,this.env(),{tags:{"collector.test":"true"},fingerprint:["collector.test"]});}let o=this.beforeSend(r)??r;return new Promise(i=>{let s=false,u=a=>{s||(s=true,clearTimeout(c),i(a));},c=setTimeout(()=>{u(e(`no answer from Collector within ${String(Ce/1e3)} s.`));},Ce);n.send(o,a=>{if(s)return;let d=wt(a);if(d!==void 0){u(e(d));return}this.logger.info(`Test event sent (${"status"in a?String(a.status):"?"}). Look for "CollectorTest" in your project: ${o.uuid}`),u({ok:true,id:o.uuid});});})}addBreadcrumb(e){this.scope.addBreadcrumb(e,this.options.maxBreadcrumbs??bt);}async flush(e){return this.transport?this.transport.flush(e):Promise.resolve(true)}setRoute(e){this.rum?.setRoute(e);}isOwnUrl(e){return this.endpointBase!==void 0&&e.startsWith(`${this.endpointBase}/`)}close(){this.closed=true;try{this.rum?.close();}catch(e){this.logger.debug("RUM didn't close cleanly",e);}if(v===this){v=void 0;for(let[e,n]of D)try{n()&&D.delete(e);}catch{}}for(let e of this.cleanups.splice(0).reverse())try{e();}catch(n){this.logger.debug("cleanup failed",n);}}env(){let{win:e}=this;return this.classify??(this.classify={fn:me(e.document,e.location.origin)}),{options:this.options,scope:this.scope,origin:e.location.origin,href:e.location.href,userAgent:e.navigator.userAgent,session:this.rum?.session,classify:this.classify.fn}}capture(e){let n=this.transport;if(!n||this.closed||n.disabled)return;let r=e();if(fe(r,this.ignore)){this.logger.debug("ignored",r.exception?.type??r.message);return}let o=Date.now();if(this.deduper.isDuplicate(r,o))return;let i=this.beforeSend(r);if(i){if(!this.rateGuard.take(o)){this.logger.debug("too many events, dropped one");return}return n.send(i),i.uuid}}beforeSend(e){let n=this.options.beforeSend;if(!n)return e;let r;try{r=n(e);}catch(o){return this.logger.debug("beforeSend threw; sending the event unchanged",o),e}if(r!==null){if((typeof r=="object"||typeof r=="function")&&"then"in r&&typeof r.then=="function"){this.logger.warnOnce("beforeSend returned a Promise, so the event was dropped. It must return the event (or null) right away, not async.");return}if(typeof r!="object"||Array.isArray(r)||!("uuid"in r)||typeof r.uuid!="string"){this.logger.debug("beforeSend returned neither an event nor null; dropped",r);return}return r}}};var Mn="0.5.0",p,O,Y=new S,Z=false,q;function L(){return p?.scope??Y}function y(t,e){try{return t()}catch(n){return p?.logger.debug("internal error",n),e}}function Un(t={}){y(()=>{if(typeof window>"u")return;let e=L();p?.close(),q?.(),p=new j(kt(t),window,e),Le();let n=()=>{y(Le,void 0);};document.addEventListener("turbo:load",n),q=()=>{document.removeEventListener("turbo:load",n);},O&&p.setRoute(O.name),O=void 0,t.debug===!0?Object.defineProperty(window,J,{value:{test:Tt},configurable:!0,writable:!0}):Reflect.deleteProperty(window,J);},void 0);}var J="__collector";function kt(t){let e={...t},n=t.dsn??E("collector-dsn"),r=t.environment??E("collector-environment"),o=t.release??E("collector-release");return n!==void 0&&(e.dsn=n),r!==void 0&&(e.environment=r),o!==void 0&&(e.release=o),e}function Le(){if(Z)return;let t=E("collector-user");L().setUser(t===void 0?null:{id:t});}async function Tt(){let t=()=>{let e="init() hasn't run on this page (or this isn't a browser).";return console.warn(`[collector] Test event not sent: ${e}`),{ok:false,reason:e}};return y(async()=>p?p.test():Promise.resolve(t()),Promise.resolve({ok:false,reason:"internal error."}))}function In(t,e){return y(()=>p?.captureException(t,e),void 0)}function $n(t,e){return y(()=>p?.captureMessage(t,e),void 0)}function Fn(t){y(()=>{Z=!0,L().setUser(t);},void 0);}function Bn(t,e){y(()=>{L().setTag(t,e);},void 0);}function Pn(t){y(()=>{L().setTags(t);},void 0);}function Dn(t){y(()=>{p?p.addBreadcrumb(t):Y.addBreadcrumb(t,50);},void 0);}async function jn(t){return y(async()=>p?.flush(t)??Promise.resolve(true),Promise.resolve(false))}function qn(t){y(()=>{p?p.setRoute(t):O={name:t};},void 0);}function Hn(){y(()=>{p?.close(),p=void 0,q?.(),q=void 0,Y=new S,O=void 0,Z=!1,typeof window<"u"&&Reflect.deleteProperty(window,J);},void 0);}re(import.meta.url);
7
+ export{Mn as SDK_VERSION,Dn as addBreadcrumb,In as captureException,$n as captureMessage,Hn as close,jn as flush,Un as init,qn as setRoute,Bn as setTag,Pn as setTags,Fn as setUser,Tt as test};
package/dist/index.cjs CHANGED
@@ -69,6 +69,10 @@ function rumUrl(base, url) {
69
69
  }
70
70
  }
71
71
 
72
+ // src/self.ts
73
+ var file;
74
+ var sdkFile = () => file;
75
+
72
76
  // src/stacktrace.ts
73
77
  var MAX_FRAMES = 250;
74
78
  var V8 = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/;
@@ -154,7 +158,7 @@ function toFrames(raw, opts) {
154
158
  }
155
159
  return frames;
156
160
  }
157
- function toFrame(raw, { origin, inAppUrls }) {
161
+ function toFrame(raw, { origin, inAppUrls, classify, sdkFile: sdkFile2 }) {
158
162
  let url;
159
163
  try {
160
164
  url = new URL(raw.url, origin);
@@ -163,10 +167,16 @@ function toFrame(raw, { origin, inAppUrls }) {
163
167
  }
164
168
  const webpackInternal = raw.url.startsWith("webpack-internal://");
165
169
  const sameOrigin = url?.origin === origin || webpackInternal;
166
- let file = stripUrl(raw.url);
167
- if (url && !webpackInternal) file = sameOrigin ? url.pathname : stripUrl(url.href);
168
- const inApp = inAppUrls ? inAppUrls.some((p) => typeof p === "string" ? raw.url.includes(p) : p.test(raw.url)) : sameOrigin && !isExtensionUrl(raw.url) && !VENDOR_PATTERNS.some((p) => p.test(file));
169
- const frame = { module: normalizeModule(file), function: raw.function ?? "?", file, in_app: inApp };
170
+ let file2 = stripUrl(raw.url);
171
+ if (url && !webpackInternal) file2 = sameOrigin ? url.pathname : stripUrl(url.href);
172
+ const inApp = isInApp();
173
+ function isInApp() {
174
+ if (inAppUrls) return inAppUrls.some((p) => typeof p === "string" ? raw.url.includes(p) : p.test(raw.url));
175
+ const verdict = url === void 0 ? void 0 : classify?.(url.href);
176
+ if (verdict !== void 0) return verdict === "app";
177
+ return sameOrigin && !isExtensionUrl(raw.url) && !VENDOR_PATTERNS.some((p) => p.test(file2));
178
+ }
179
+ const frame = { module: normalizeModule(file2), function: raw.function ?? "?", file: file2, in_app: inApp };
170
180
  if (raw.line !== void 0) frame.line = raw.line;
171
181
  if (raw.column !== void 0) frame.column = raw.column;
172
182
  return frame;
@@ -195,7 +205,7 @@ function errorType(error) {
195
205
  function eventFromException(error, env, ctx, mechanism = "manual") {
196
206
  const event = baseEvent(env, ctx);
197
207
  if (isErrorLike(error)) {
198
- const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls }) : [];
208
+ const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls, classify: env.classify, sdkFile: sdkFile() }) : [];
199
209
  event.exception = { type: errorType(error), message: truncate(String(error.message), MAX_MESSAGE) };
200
210
  if (frames.length > 0) event.exception.frames = frames;
201
211
  } else {
@@ -229,7 +239,7 @@ function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {
229
239
  platform: "javascript",
230
240
  level: toLevel(ctx.level),
231
241
  request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
232
- sdk: { name: SDK_NAME, version: "0.4.0" }
242
+ sdk: { name: SDK_NAME, version: "0.5.0" }
233
243
  };
234
244
  const environment = environmentOf(options);
235
245
  if (environment !== void 0) event.environment = environment;
@@ -326,6 +336,52 @@ function errorFromLocation(e) {
326
336
  return error;
327
337
  }
328
338
 
339
+ // src/meta.ts
340
+ function readMeta(name) {
341
+ if (typeof document === "undefined") return void 0;
342
+ const content = document.querySelector(`meta[name="${name}"]`)?.content.trim();
343
+ return content === void 0 || content === "" ? void 0 : content;
344
+ }
345
+
346
+ // src/importmap.ts
347
+ var isBare = (specifier) => !/^(?:\.{0,2}\/|[a-z][a-z\d+.-]*:)/i.test(specifier);
348
+ function pinsOf(doc) {
349
+ const script = doc.querySelector('script[type="importmap"]');
350
+ const text = script?.textContent;
351
+ if (text === void 0 || text === "") return void 0;
352
+ let map;
353
+ try {
354
+ map = JSON.parse(text);
355
+ } catch {
356
+ return void 0;
357
+ }
358
+ const imports = typeof map === "object" && map !== null && "imports" in map ? map.imports : void 0;
359
+ if (typeof imports !== "object" || imports === null) return void 0;
360
+ const pins = [];
361
+ for (const [specifier, target] of Object.entries(imports)) {
362
+ if (typeof target !== "string" || !isBare(specifier)) continue;
363
+ try {
364
+ pins.push({ specifier, url: stripUrl(new URL(target, doc.baseURI).href), prefix: specifier.endsWith("/") });
365
+ } catch {
366
+ }
367
+ }
368
+ return pins.sort((a, b) => a.prefix === b.prefix ? b.url.length - a.url.length : Number(a.prefix) - Number(b.prefix));
369
+ }
370
+ var listed = (list, specifier) => list.some((entry) => entry === specifier || entry.endsWith("/") && specifier.startsWith(entry));
371
+ function importMapClassifier(doc, origin) {
372
+ const pins = pinsOf(doc);
373
+ if (!pins || pins.length === 0) return void 0;
374
+ const own = readMeta("collector-in-app")?.split(/[\s,]+/).filter((entry) => entry !== "");
375
+ return (url) => {
376
+ const clean = stripUrl(url);
377
+ const pin = pins.find((p) => p.prefix ? clean.startsWith(p.url) : clean === p.url);
378
+ if (!pin) return void 0;
379
+ const specifier = pin.prefix ? pin.specifier + clean.slice(pin.url.length) : pin.specifier;
380
+ if (own) return listed(own, specifier) ? "app" : "dependency";
381
+ return specifier.startsWith("@") || !pin.url.startsWith(`${origin}/`) ? "dependency" : void 0;
382
+ };
383
+ }
384
+
329
385
  // src/heartbeat.ts
330
386
  var HEARTBEAT_DELAY_MS = 5e3;
331
387
  var STORAGE_PREFIX = "collector:heartbeat:";
@@ -359,7 +415,7 @@ async function beat({ url, key, fetch, options, logger }) {
359
415
  if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
360
416
  let status;
361
417
  try {
362
- const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.4.0" }, environment, release });
418
+ const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.5.0" }, environment, release });
363
419
  const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
364
420
  ({ status } = response);
365
421
  } catch (error) {
@@ -374,6 +430,33 @@ async function beat({ url, key, fetch, options, logger }) {
374
430
  }
375
431
  }
376
432
 
433
+ // src/describe.ts
434
+ var MAX_KEYS = 10;
435
+ var MAX_STRING = 100;
436
+ function describeValue(value, nested = false) {
437
+ if (typeof value === "string") return nested ? JSON.stringify(truncate(value, MAX_STRING)) : value;
438
+ if (value === null || typeof value !== "object") {
439
+ return typeof value === "function" ? `[Function ${value.name !== "" ? value.name : "anonymous"}]` : String(value);
440
+ }
441
+ const v = value;
442
+ if (value instanceof Error || typeof v.message === "string" && typeof v.name === "string") {
443
+ return `${String(v.name)}: ${String(v.message)}`;
444
+ }
445
+ if (typeof v.nodeType === "number") return typeof v.tagName === "string" ? `<${v.tagName.toLowerCase()}>` : "[Node]";
446
+ if (nested) return Array.isArray(value) ? `[Array(${String(value.length)})]` : "{\u2026}";
447
+ if (Array.isArray(value)) {
448
+ const items = value.slice(0, MAX_KEYS).map((x) => describeValue(x, true));
449
+ return `[${items.join(", ")}${value.length > MAX_KEYS ? ", \u2026" : ""}]`;
450
+ }
451
+ try {
452
+ const keys = Object.keys(value);
453
+ const shown = keys.slice(0, MAX_KEYS).map((k) => `${k}: ${describeValue(value[k], true)}`);
454
+ return `{${shown.join(", ")}${keys.length > MAX_KEYS ? ", \u2026" : ""}}`;
455
+ } catch {
456
+ return "{\u2026}";
457
+ }
458
+ }
459
+
377
460
  // src/instrument/common.ts
378
461
  var ORIGINAL = "__collector_original__";
379
462
  function wrap(obj, name, make) {
@@ -431,31 +514,6 @@ function requestMessage(method, url, status) {
431
514
 
432
515
  // src/instrument/console.ts
433
516
  var LEVELS2 = { error: "error", warn: "warning", log: "info", info: "info" };
434
- var MAX_KEYS = 10;
435
- var MAX_STRING = 100;
436
- function describeValue(value, nested = false) {
437
- if (typeof value === "string") return nested ? JSON.stringify(truncate(value, MAX_STRING)) : value;
438
- if (value === null || typeof value !== "object") {
439
- return typeof value === "function" ? `[Function ${value.name !== "" ? value.name : "anonymous"}]` : String(value);
440
- }
441
- const v = value;
442
- if (value instanceof Error || typeof v.message === "string" && typeof v.name === "string") {
443
- return `${String(v.name)}: ${String(v.message)}`;
444
- }
445
- if (typeof v.nodeType === "number") return typeof v.tagName === "string" ? `<${v.tagName.toLowerCase()}>` : "[Node]";
446
- if (nested) return Array.isArray(value) ? `[Array(${String(value.length)})]` : "{\u2026}";
447
- if (Array.isArray(value)) {
448
- const items = value.slice(0, MAX_KEYS).map((x) => describeValue(x, true));
449
- return `[${items.join(", ")}${value.length > MAX_KEYS ? ", \u2026" : ""}]`;
450
- }
451
- try {
452
- const keys = Object.keys(value);
453
- const shown = keys.slice(0, MAX_KEYS).map((k) => `${k}: ${describeValue(value[k], true)}`);
454
- return `{${shown.join(", ")}${keys.length > MAX_KEYS ? ", \u2026" : ""}}`;
455
- } catch {
456
- return "{\u2026}";
457
- }
458
- }
459
517
  function instrumentConsole(win, record, _opts) {
460
518
  const target = win.console;
461
519
  const restores = Object.keys(LEVELS2).map(
@@ -991,7 +1049,7 @@ var Client = class {
991
1049
  }
992
1050
  if (options.rum && !this.transport.disabled) {
993
1051
  try {
994
- this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.4.0" }, environment: environmentOf(options), release: releaseOf(options) });
1052
+ this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.5.0" }, environment: environmentOf(options), release: releaseOf(options) });
995
1053
  } catch (error) {
996
1054
  this.logger.debug("RUM didn't start", error);
997
1055
  }
@@ -1108,13 +1166,15 @@ var Client = class {
1108
1166
  }
1109
1167
  env() {
1110
1168
  const { win } = this;
1169
+ this.classify ?? (this.classify = { fn: importMapClassifier(win.document, win.location.origin) });
1111
1170
  return {
1112
1171
  options: this.options,
1113
1172
  scope: this.scope,
1114
1173
  origin: win.location.origin,
1115
1174
  href: win.location.href,
1116
1175
  userAgent: win.navigator.userAgent,
1117
- session: this.rum?.session
1176
+ session: this.rum?.session,
1177
+ classify: this.classify.fn
1118
1178
  };
1119
1179
  }
1120
1180
  capture(build) {
@@ -1160,10 +1220,12 @@ var Client = class {
1160
1220
  };
1161
1221
 
1162
1222
  // src/index.ts
1163
- var SDK_VERSION = "0.4.0";
1223
+ var SDK_VERSION = "0.5.0";
1164
1224
  var client;
1165
1225
  var pendingRoute;
1166
1226
  var pendingScope = new Scope();
1227
+ var userFromApp = false;
1228
+ var stopPageListener;
1167
1229
  function scope() {
1168
1230
  return client?.scope ?? pendingScope;
1169
1231
  }
@@ -1175,12 +1237,21 @@ function safely(fn, fallback) {
1175
1237
  return fallback;
1176
1238
  }
1177
1239
  }
1178
- function init(options) {
1240
+ function init(options = {}) {
1179
1241
  safely(() => {
1180
1242
  if (typeof window === "undefined") return;
1181
1243
  const kept = scope();
1182
1244
  client?.close();
1183
- client = new Client(options, window, kept);
1245
+ stopPageListener?.();
1246
+ client = new Client(withMeta(options), window, kept);
1247
+ userFromMeta();
1248
+ const onPageLoad = () => {
1249
+ safely(userFromMeta, void 0);
1250
+ };
1251
+ document.addEventListener("turbo:load", onPageLoad);
1252
+ stopPageListener = () => {
1253
+ document.removeEventListener("turbo:load", onPageLoad);
1254
+ };
1184
1255
  if (pendingRoute) client.setRoute(pendingRoute.name);
1185
1256
  pendingRoute = void 0;
1186
1257
  if (options.debug === true) Object.defineProperty(window, CONSOLE_HANDLE, { value: { test }, configurable: true, writable: true });
@@ -1188,6 +1259,21 @@ function init(options) {
1188
1259
  }, void 0);
1189
1260
  }
1190
1261
  var CONSOLE_HANDLE = "__collector";
1262
+ function withMeta(options) {
1263
+ const resolved = { ...options };
1264
+ const dsn = options.dsn ?? readMeta("collector-dsn");
1265
+ const environment = options.environment ?? readMeta("collector-environment");
1266
+ const release = options.release ?? readMeta("collector-release");
1267
+ if (dsn !== void 0) resolved.dsn = dsn;
1268
+ if (environment !== void 0) resolved.environment = environment;
1269
+ if (release !== void 0) resolved.release = release;
1270
+ return resolved;
1271
+ }
1272
+ function userFromMeta() {
1273
+ if (userFromApp) return;
1274
+ const id = readMeta("collector-user");
1275
+ scope().setUser(id === void 0 ? null : { id });
1276
+ }
1191
1277
  async function test() {
1192
1278
  const notInitialized = () => {
1193
1279
  const reason = "init() hasn't run on this page (or this isn't a browser).";
@@ -1204,6 +1290,7 @@ function captureMessage(message, context) {
1204
1290
  }
1205
1291
  function setUser(user) {
1206
1292
  safely(() => {
1293
+ userFromApp = true;
1207
1294
  scope().setUser(user);
1208
1295
  }, void 0);
1209
1296
  }
@@ -1236,8 +1323,11 @@ function close() {
1236
1323
  safely(() => {
1237
1324
  client?.close();
1238
1325
  client = void 0;
1326
+ stopPageListener?.();
1327
+ stopPageListener = void 0;
1239
1328
  pendingScope = new Scope();
1240
1329
  pendingRoute = void 0;
1330
+ userFromApp = false;
1241
1331
  if (typeof window !== "undefined") Reflect.deleteProperty(window, CONSOLE_HANDLE);
1242
1332
  }, void 0);
1243
1333
  }
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { B as Breadcrumb, C as CaptureContext, L as Level, a as CollectorOptions, T as TestResult } from './types-CTnanJxh.cjs';
2
- export { b as BreadcrumbKind, c as CollectorEvent, F as Frame, R as RequestTiming, d as RumContext, e as RumHandle, f as RumPlugin } from './types-CTnanJxh.cjs';
1
+ import { B as Breadcrumb, C as CaptureContext, L as Level, a as CollectorOptions, T as TestResult } from './types-ml-o_-mr.cjs';
2
+ export { b as BreadcrumbKind, c as CollectorEvent, F as Frame, R as RequestTiming, d as RumContext, e as RumHandle, f as RumPlugin } from './types-ml-o_-mr.cjs';
3
3
 
4
4
  /** The version of this SDK, as sent in every event's `sdk.version`. */
5
5
  declare const SDK_VERSION: string;
@@ -13,10 +13,14 @@ declare const SDK_VERSION: string;
13
13
  * Collector.init({ dsn: "https://clt_…@app.clt.chrom.ar" });
14
14
  * ```
15
15
  *
16
+ * Without options, it reads them from the page's meta tags:
17
+ * `<meta name="collector-dsn">`, `collector-environment` and
18
+ * `collector-release`. Options you pass win over the tags.
19
+ *
16
20
  * Without a `dsn`, nothing is captured or sent. Calling it again replaces the
17
21
  * options. Safe to import during server-side rendering: it does nothing there.
18
22
  */
19
- declare function init(options: CollectorOptions): void;
23
+ declare function init(options?: CollectorOptions): void;
20
24
  /**
21
25
  * Sends one test error, to check your setup end to end. Resolves to
22
26
  * `{ ok: true, id }` once Collector accepts it, or `{ ok: false, reason }`,
@@ -31,7 +35,10 @@ declare function test(): Promise<TestResult>;
31
35
  declare function captureException(error: unknown, context?: CaptureContext): string | undefined;
32
36
  /** Reports something that isn't an error: `captureMessage("Payment slow", "warning")`. */
33
37
  declare function captureMessage(message: string, context?: CaptureContext | Level): string | undefined;
34
- /** Attaches your user's id to the following events. An id, not personal data. `null` clears it. */
38
+ /**
39
+ * Attaches your user's id to the following events. An id, not personal data. `null` clears it.
40
+ * From then on, the `collector-user` meta tag is ignored.
41
+ */
35
42
  declare function setUser(user: {
36
43
  id: string | number;
37
44
  } | null): void;