@interfere/react 12.3.4 → 12.4.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/README.md +6 -0
- package/dist/{api-DSUjs8zG.d.mts → api-BXjfYV5Z.d.mts} +1 -0
- package/dist/api-C8aG7li1.mjs +1 -0
- package/dist/{delivery-D9hzPDs9.mjs → delivery-D7hULClu.mjs} +1 -1
- package/dist/error-boundary.d.mts +1 -1
- package/dist/export-filter-CnyAaPct.mjs +1 -0
- package/dist/exporter-CCgTznZ0.mjs +1 -0
- package/dist/exporter-logs-BbzSiQJi.mjs +1 -0
- package/dist/{index-DpkTHU1a.d.mts → index-CPrYhbZR.d.mts} +1 -1
- package/dist/ingest-backoff-BdBT-jss.mjs +1 -0
- package/dist/internal/capture/capture-boundary.d.mts +1 -1
- package/dist/internal/capture/capture.d.mts +1 -1
- package/dist/internal/ingest-backoff/ingest-backoff.d.mts +3 -2
- package/dist/internal/ingest-backoff/ingest-backoff.mjs +1 -1
- package/dist/internal/kernel-registry.d.mts +1 -1
- package/dist/internal/kernel.d.mts +1 -1
- package/dist/internal/kernel.mjs +1 -1
- package/dist/internal/otel/export-filter.d.mts +2 -2
- package/dist/internal/otel/export-filter.mjs +1 -1
- package/dist/internal/otel/exporter-logs.mjs +1 -1
- package/dist/internal/otel/exporter.mjs +1 -1
- package/dist/internal/otel/index.d.mts +2 -2
- package/dist/internal/otel/index.mjs +1 -1
- package/dist/internal/otel/keepalive-chunks.d.mts +6 -0
- package/dist/internal/otel/keepalive-chunks.mjs +1 -0
- package/dist/internal/otel/page-scope-context-manager.d.mts +1 -1
- package/dist/internal/otel/page-scope-context-manager.mjs +1 -1
- package/dist/internal/otel/provider.d.mts +1 -1
- package/dist/internal/otel/provider.mjs +1 -1
- package/dist/internal/page-lifecycle/keepalive-budget.d.mts +2 -2
- package/dist/internal/page-lifecycle/keepalive-budget.mjs +1 -1
- package/dist/internal/plugins/plugin-runtime.d.mts +1 -1
- package/dist/internal/plugins/plugin-runtime.mjs +1 -1
- package/dist/internal/react-context.d.mts +1 -1
- package/dist/internal/react-dom-keys.d.mts +3 -0
- package/dist/internal/react-dom-keys.mjs +1 -0
- package/dist/internal/sw-queue-protocol.d.mts +2 -0
- package/dist/internal/sw-queue-protocol.mjs +1 -0
- package/dist/internal/sw-queue.mjs +1 -1
- package/dist/internal/version.mjs +1 -1
- package/dist/internal/wrapper-singleton.d.mts +1 -1
- package/dist/internal/wrapper-singleton.mjs +1 -1
- package/dist/keepalive-budget-BfoHXD04.mjs +1 -0
- package/dist/keepalive-chunks-BZv3PhHT.mjs +1 -0
- package/dist/kernel-zu11DwyQ.mjs +1 -0
- package/dist/msw-C0yLYJU2.mjs +255 -0
- package/dist/page-scope-context-manager-Bs-m4fv7.mjs +1 -0
- package/dist/{page-scope-context-manager-r92ZMJok.d.mts → page-scope-context-manager-DUhBvuAz.d.mts} +2 -2
- package/dist/{plugin-runtime-DSj0FM1Q.mjs → plugin-runtime-DgB1_Xc5.mjs} +1 -1
- package/dist/plugins/device.d.mts +1 -1
- package/dist/plugins/errors.d.mts +1 -1
- package/dist/plugins/lib/loader.d.mts +1 -1
- package/dist/plugins/lib/types.d.mts +1 -1
- package/dist/plugins/logs.d.mts +1 -1
- package/dist/plugins/page-events.d.mts +1 -1
- package/dist/plugins/rage-clicks.d.mts +1 -1
- package/dist/plugins/replay/index.d.mts +1 -1
- package/dist/plugins/replay/index.mjs +1 -1
- package/dist/plugins/replay/upload/delivery.d.mts +1 -1
- package/dist/plugins/replay/upload/delivery.mjs +1 -1
- package/dist/{provider-D4QjZp3L.d.mts → provider-BMMGZWyS.d.mts} +5 -4
- package/dist/provider-DwCQ_vj0.mjs +1 -0
- package/dist/{provider-cUByhzgv.d.mts → provider-Dy0mVCx5.d.mts} +4 -2
- package/dist/provider.d.mts +1 -1
- package/dist/react-dom-keys-BIJuLkQR.mjs +1 -0
- package/dist/react-error-handler.d.mts +1 -1
- package/dist/{session-retry-TrzzihIM.mjs → session-retry-Dgkk0yui.mjs} +1 -1
- package/dist/sw-queue-protocol-DnTSOWxy.mjs +1 -0
- package/dist/sw-queue-protocol-DqP1EQtQ.d.mts +22 -0
- package/dist/tracking/api.d.mts +1 -1
- package/dist/tracking/api.mjs +1 -1
- package/dist/tracking/lifecycle.fixture.d.mts +73 -0
- package/dist/tracking/lifecycle.fixture.mjs +1 -0
- package/dist/tracking/registration.fixture.d.mts +1 -1
- package/dist/tracking/registration.fixture.mjs +1 -255
- package/dist/tracking/session-retry.mjs +1 -1
- package/dist/{version-DusHm2Q4.mjs → version-CtEAnX65.mjs} +1 -1
- package/package.json +3 -4
- package/dist/api-DvHT4Dyw.mjs +0 -1
- package/dist/export-filter-Cixywxpu.mjs +0 -1
- package/dist/exporter-De0h9YP5.mjs +0 -1
- package/dist/exporter-logs-DS2AXWnV.mjs +0 -1
- package/dist/ingest-backoff-B1OeEV3h.mjs +0 -1
- package/dist/keepalive-budget-DeafGnVZ.mjs +0 -1
- package/dist/kernel-BVG-7Zau.mjs +0 -1
- package/dist/page-scope-context-manager-DhArvVJ_.mjs +0 -1
- package/dist/provider-CElaujE6.mjs +0 -1
package/README.md
CHANGED
|
@@ -194,6 +194,12 @@ Finish attribute mutations synchronously in `onEnd`, before it returns. OpenTele
|
|
|
194
194
|
|
|
195
195
|
The SDK calls each processor's `forceFlush` during flush and `shutdown` during disposal. Use a fresh processor instance for each SDK initialization and do not share it with another provider. `tracing: false` skips tracing setup, including custom processors.
|
|
196
196
|
|
|
197
|
+
## Trace export and context
|
|
198
|
+
|
|
199
|
+
The SDK batches ended spans and sends them every 60 seconds, or sooner when 200 spans are waiting. When the page is hidden or unloaded, it sends everything still queued at once with a keepalive request. Spans still queued when a tab is killed without a hide event, such as a crash, are lost. Logs are sent every 5 seconds.
|
|
200
|
+
|
|
201
|
+
The SDK tracks the active span without zone.js. A click or submit span ends when its synchronous event handler returns. Spans started after an `await` in that handler, including fetch and XHR requests, are children of the page span instead of the click span. If your app loads zone.js itself, as Angular does, the SDK does not use it.
|
|
202
|
+
|
|
197
203
|
## Documentation
|
|
198
204
|
|
|
199
205
|
Visit [interfere.com/docs](https://interfere.com/docs) for the full documentation.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as createLogger}from"./log-D6Ht--tv.mjs";import{t as ActivityMonitor}from"./activity-oYlZ5aa1.mjs";import{n as fetchIngest}from"./ingest-backoff-BdBT-jss.mjs";import{t as DeviceManager}from"./device-DRK7hhLi.mjs";import{t as GeoDetector}from"./geo-D2wa9bGs.mjs";import{t as SessionManager}from"./session-C30CtCVv.mjs";import{t as SessionRetry}from"./session-retry-Dgkk0yui.mjs";import{omitUndefined}from"@interfere/helpers/omit-undefined";import{InterfereClient,InterfereError}from"@interfere/javascript";const log=createLogger(`tracking`);function syncKey(sessionId,deviceId,fpHash){return`${sessionId}|${deviceId??``}|${fpHash??``}`}var SessionTracker=class{client;device;geo;mgr=null;activity=new ActivityMonitor;currentIdentity=null;identifiedSessionId=null;identifiedDeviceId=null;lastSyncedKey=null;inflightSyncKey=null;syncAttemptMs=0;generation=0;syncRetry=new SessionRetry;syncRetryKey=null;identityStarted=!1;constructor(opts){this.client=new InterfereClient({...opts.target,maxRetries:0,timeoutInSeconds:10,fetch:Object.assign(async(input,init)=>fetchIngest(input,async()=>(opts.fetcher??globalThis.fetch)(input,{...init,credentials:`omit`,keepalive:!0})),opts.fetcher??globalThis.fetch)}),this.device=opts.device??new DeviceManager,this.geo=opts.geo??new GeoDetector}start(){this.mgr=new SessionManager(id=>{this.onRotate(id)}),this.activity.start({markActivity:()=>{this.markActivity()},reset:()=>{this.rotateSession()},startedAt:()=>this.getSessionStartedAt()})}startDeviceIdentity(){this.identityStarted||(this.invalidateSync(),this.identityStarted=!0,this.device.init(),this.geo.detect(),this.backfillIdentity())}discardDeviceIdentity(){this.invalidateSync(),this.identityStarted=!1,this.device.clear(),this.geo.clear()}async backfillIdentity(){let gen=this.generation;if(await Promise.resolve(),gen!==this.generation||!this.identityStarted)return;let initialSessionId=this.mgr?.getSessionId()??null,initialFpHash=this.device.getFpHash();initialSessionId&&await this.syncSession(initialSessionId,this.device.getDeviceId(),initialFpHash),this.currentIdentity&&this.identify(this.currentIdentity);let fpHash=await this.device.whenFingerprintReady(),sessionId=this.mgr?.getSessionId()??null;gen===this.generation&&this.identityStarted&&sessionId&&fpHash!==initialFpHash&&this.syncSession(sessionId,this.device.getDeviceId(),fpHash)}onSessionPause(handler){return this.activity.onPause(handler)}onSessionExceptionWhilePaused(handler){return this.activity.onExceptionWhilePaused(handler)}noteException(){this.activity.noteException()}onSessionResume(handler){return this.activity.onResume(handler)}sessionId(){let id=this.mgr?.getSessionId()??null;return id&&this.ensureSynced(id),id}windowId(){return this.mgr?.getWindowId()??null}markActivity(){this.mgr?.markActivity()}getSessionStartedAt(){return this.mgr?.getSessionStartedAt()??0}getDeviceId(){return this.device.getDeviceId()}getFpHash(){return this.device.getFpHash()}getIdentity(){return this.currentIdentity}async identify(params){if(!this.mgr)return;let sessionId=this.mgr.getSessionId();if(this.identifiedSessionId===sessionId&&this.identifiedDeviceId===this.device.getDeviceId()){log.debug(`skipped, already identified for session %s`,sessionId);return}this.currentIdentity=params,this.identifiedSessionId=sessionId,this.identifiedDeviceId=this.device.getDeviceId();let gen=this.generation,[fpHash,country]=await Promise.all([this.device.whenFingerprintReady(),this.geo.detect()]),deviceId=this.device.getDeviceId();if(gen!==this.generation){this.identifiedSessionId=null;return}log.info(`POST session %s → identify`,sessionId),this.postIdentify(sessionId,omitUndefined({deviceId,fpHash,sessionId,...params,country:country||void 0}))}async postIdentify(sessionId,body){try{await this.client.sessions.identifySession(body)}catch{this.identifiedSessionId=null,log.warn(`identify failed for session %s`,sessionId)}}clearIdentity(){this.currentIdentity=null,this.identifiedSessionId=null,this.identifiedDeviceId=null}reset(){this.invalidateSync(),this.clearIdentity(),this.identityStarted&&this.device.reset(),this.mgr?.reset()}rotateSession(){this.mgr?.reset()}dispose(){this.activity.stop(),this.invalidateSync(),this.clearIdentity(),this.mgr=null}invalidateSync(){this.generation+=1,this.syncRetry.reset(),this.syncRetryKey=null,this.lastSyncedKey=null,this.inflightSyncKey=null,this.syncAttemptMs=0}currentSyncKey(){let sessionId=this.mgr?.sessionId;return sessionId?syncKey(sessionId,this.device.getDeviceId(),this.device.getFpHash()):null}ensureSynced(sessionId){let deviceId=this.device.getDeviceId(),fpHash=this.device.getFpHash(),key=syncKey(sessionId,deviceId,fpHash);this.lastSyncedKey!==key&&this.inflightSyncKey!==key&&(Date.now()-this.syncAttemptMs<5e3||this.syncSession(sessionId,deviceId,fpHash))}async syncSession(sessionId,deviceId,fpHash){let key=syncKey(sessionId,deviceId,fpHash);if(this.lastSyncedKey===key||this.inflightSyncKey===key)return;this.syncRetryKey!==key&&(this.syncRetry.reset(),this.syncRetryKey=key),this.syncRetry.cancel();let{generation}=this;this.inflightSyncKey=key,this.syncAttemptMs=Date.now();try{await this.client.sessions.createSession({sessionId,deviceId,fpHash}),generation===this.generation&&key===this.currentSyncKey()&&(this.lastSyncedKey=key,this.syncRetry.reset())}catch(error){log.warn(`session sync failed`),error instanceof InterfereError&&generation===this.generation&&key===this.currentSyncKey()&&this.syncRetry.schedule(error,()=>{let current=this.mgr?.sessionId;generation===this.generation&¤t&&this.ensureSynced(current)})}finally{generation===this.generation&&this.inflightSyncKey===key&&(this.inflightSyncKey=null)}}async onRotate(sessionId){this.syncAttemptMs=Date.now();let gen=this.generation;try{await Promise.resolve();let fpHash=this.device.getFpHash(),deviceId=this.device.getDeviceId();if(gen!==this.generation)return;log.debug(`POST session %s (device=%s fp=%s)`,sessionId,deviceId??`pending`,fpHash??`none`),this.syncSession(sessionId,deviceId,fpHash)}catch{}}};export{SessionTracker as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as createLogger}from"./log-D6Ht--tv.mjs";import{t as reserveKeepaliveBody}from"./keepalive-budget-
|
|
1
|
+
import{t as createLogger}from"./log-D6Ht--tv.mjs";import{t as reserveKeepaliveBody}from"./keepalive-budget-BfoHXD04.mjs";import{t as gzipForUnload}from"./unload-gzip-WX9FyWPs.mjs";import{t as uploadReplayChunk}from"./upload-D55WVf_o.mjs";import{omitUndefined}from"@interfere/helpers/omit-undefined";const log=createLogger(`replay`),REPLAY_TRACER_NAME=`@interfere/react/replay`,textEncoder=new TextEncoder,FATAL_STATUSES=new Set([401,403,413]);function classifyRejection(status){return status===409?`skipped`:FATAL_STATUSES.has(status)?`fatal`:`retryable`}async function prepareBody(compressor,rawBytes){if(!compressor.gzip)return{body:rawBytes,encoding:null,release:null};try{return{body:await compressor.gzip(rawBytes),encoding:`gzip`,release:null}}catch(error){return log.warn(`gzip failed for chunk; sending uncompressed: %o`,error),{body:rawBytes,encoding:null,release:null}}}function prepareUnloadBody(rawBytes){let rawRelease=reserveKeepaliveBody(rawBytes.byteLength);if(rawRelease)return{body:rawBytes,encoding:null,release:rawRelease};let compressed=gzipForUnload(rawBytes);return compressed?{body:compressed,encoding:`gzip`,release:reserveKeepaliveBody(compressed.byteLength)}:{body:rawBytes,encoding:null,release:null}}function encodeReplayMeta(chunk,payload){return btoa(JSON.stringify({activityCount:payload.activityCount,eventCount:payload.eventCount,firstTs:payload.firstTs,hasFullSnapshot:payload.hasFullSnapshot,lastTs:payload.lastTs,segmentId:chunk.segmentId,windowId:chunk.windowId}))}async function deliverChunk({ctx,chunk,target,compressor,payload,trigger,unload}){let sessionId=ctx.getSessionId();if(!sessionId)return`ok`;let rawBytes=textEncoder.encode(payload.bodyJson),uncompressedBytes=rawBytes.byteLength,prepared=unload?prepareUnloadBody(rawBytes):await prepareBody(compressor,rawBytes),headers={"x-replay-meta":encodeReplayMeta(chunk,payload)};prepared.encoding===`gzip`&&(headers[`content-encoding`]=`gzip`);let keepalive=prepared.release!==null,response;try{let upload=await uploadReplayChunk(target,sessionId,prepared.body,headers,{keepalive});if(!upload.ok)return await upload.body?.cancel(),classifyRejection(upload.status);response=await upload.json()}catch(error){return log.warn(`replay chunk upload failed: %o`,error),`retryable`}finally{prepared.release?.()}let objectKey=typeof response==`object`&&response&&`objectKey`in response&&typeof response.objectKey==`string`?response.objectKey:null;if(trigger===void 0&&!unload)return`ok`;let attributes=omitUndefined({"replay.chunk.size_bytes":uncompressedBytes,"replay.chunk.event_count":payload.eventCount,"replay.chunk.uri":objectKey||void 0,"replay.chunk.compressed_bytes":prepared.encoding===`gzip`?prepared.body.byteLength:void 0,"replay.chunk.first_event_ts":payload.firstTs??void 0,"replay.chunk.last_event_ts":payload.lastTs??void 0,"replay.chunk.trigger":trigger,"replay.chunk.unload":unload||void 0,"replay.chunk.keepalive":unload?keepalive:void 0});return ctx.getTracer(REPLAY_TRACER_NAME).startSpan(`replay.chunk`,{attributes}).end(),`ok`}export{deliverChunk as n,REPLAY_TRACER_NAME as t};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as InterfereContextValue, i as InterfereContext } from "./provider-
|
|
1
|
+
import { a as InterfereContextValue, i as InterfereContext } from "./provider-BMMGZWyS.mjs";
|
|
2
2
|
import { Component, ContextType, ErrorInfo, ReactNode } from "react";
|
|
3
3
|
//#region src/error-boundary.d.ts
|
|
4
4
|
export interface ErrorBoundaryProps {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{hrTimeToMilliseconds}from"@opentelemetry/core";function shouldExportSpan(span){return!(span.instrumentationScope.name===`@opentelemetry/instrumentation-long-task`&&hrTimeToMilliseconds(span.duration)<500)}function carriesException(span){return span.events.some(event=>event.name===`exception`)}function createExportFilterProcessor(next,onExceptionSpan){let flushScheduled=!1,flushSoon=()=>{flushScheduled||(flushScheduled=!0,queueMicrotask(()=>{flushScheduled=!1,next.forceFlush().catch(()=>{})}))};return{onStart:(span,parentContext)=>{next.onStart(span,parentContext)},onEnd:span=>{shouldExportSpan(span)&&(next.onEnd(span),carriesException(span)&&(onExceptionSpan?.(),flushSoon()))},forceFlush:async()=>next.forceFlush(),shutdown:async()=>next.shutdown()}}export{shouldExportSpan as n,createExportFilterProcessor as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as fetchIngest}from"./ingest-backoff-BdBT-jss.mjs";import{n as stampSentAt}from"./sent-at-CEM8UV3W.mjs";import{t as reserveKeepaliveBody}from"./keepalive-budget-BfoHXD04.mjs";import{t as sendInKeepaliveChunks}from"./keepalive-chunks-BZv3PhHT.mjs";import{t as PRODUCER_VERSION}from"./version-CtEAnX65.mjs";import{t as IngestLogExporter}from"./exporter-logs-BbzSiQJi.mjs";import{t as IngestMetricExporter}from"./exporter-metrics-DZYqUo6_.mjs";import{toError}from"@interfere/types/sdk/errors";import{InterfereClient,InterfereError}from"@interfere/javascript";import{TELEMETRY_EXPORT_TIMEOUT_MS,retryTelemetry}from"@interfere/helpers/retry-telemetry";import{ExportResultCode}from"@opentelemetry/core";import{JsonTraceSerializer}from"@opentelemetry/otlp-transformer";import{z}from"zod";const INGEST_IGNORE_RE=/\/drain\/v1\/(?:traces|logs|metrics)(?:\?|$)/u,AUTH_INVALID_HALT_COOLDOWN_MS=3e5,HALT_MESSAGES={release_not_found:`ingest halted: the ingest endpoint does not recognize this build's release`,public_key_rejected:`ingest paused: the ingest endpoint rejected this page's public key`};let haltReason=null,authHaltExpiresAt=0,consecutiveAuthRejections=0;function resetIngestHalt(){haltReason=null,authHaltExpiresAt=0,consecutiveAuthRejections=0}function currentHaltReason(){return haltReason===`public_key_rejected`&&Date.now()>=authHaltExpiresAt&&(haltReason=null,consecutiveAuthRejections=2),haltReason}function isIngestHalted(){return currentHaltReason()!==null}const textEncoder=new TextEncoder;function detectUnacceptableExport(error){if(currentHaltReason()!==null||error.statusCode!==422&&error.statusCode!==401)return;let body=error.body;if(typeof body==`object`&&body&&`code`in body){if(error.statusCode===422&&body.code===`RELEASE_NOT_FOUND`){haltReason=`release_not_found`,console.warn(`[interfere] the ingest endpoint does not recognize this build's release. Telemetry export is disabled for this page load. Check that source-map upload and finalization succeeded and that build and runtime use the same surface key.`);return}if(error.statusCode===401&&body.code===`AUTH_PK_INVALID`){if(consecutiveAuthRejections+=1,consecutiveAuthRejections<3)return;haltReason=`public_key_rejected`,authHaltExpiresAt=Date.now()+AUTH_INVALID_HALT_COOLDOWN_MS,console.warn(`[interfere] the ingest endpoint rejected this page's public key ${consecutiveAuthRejections} times in a row — telemetry export is paused for ${AUTH_INVALID_HALT_COOLDOWN_MS/6e4} minutes, then retried once. Check that INTERFERE_PUBLIC_KEY matches an active surface; a deleted surface's key stays rejected until the page is rebuilt with the new key.`)}}}function makeSender(input,signal){let client=new InterfereClient({...input.clientOptions,maxRetries:0,timeoutInSeconds:TELEMETRY_EXPORT_TIMEOUT_MS/1e3,fetch:Object.assign(async(url,init)=>fetchIngest(url,async()=>{let body=init?.body,bytes=typeof body==`string`?textEncoder.encode(body).byteLength:0,dispatch=async(abortSignal,keepalive)=>globalThis.fetch(url,{...init,headers:stampSentAt(new Headers(init?.headers)),credentials:`omit`,keepalive,signal:abortSignal});return retryTelemetry(async abortSignal=>{let release=reserveKeepaliveBody(bytes,32e3);if(release===null)return dispatch(abortSignal,!1);try{return await dispatch(abortSignal,!0)}catch(error){if(!(error instanceof TypeError)||abortSignal.aborted)throw error}finally{release()}return dispatch(abortSignal,!1)},init?.signal)}),globalThis.fetch)});return((payload,resultCallback)=>{if(!payload||payload.byteLength===0){resultCallback({code:ExportResultCode.SUCCESS});return}let reason=currentHaltReason();if(reason!==null){resultCallback({code:ExportResultCode.FAILED,error:Error(HALT_MESSAGES[reason])});return}(async()=>{try{let body=z.record(z.string(),z.unknown()).parse(JSON.parse(new TextDecoder().decode(payload)));await client.drain.otlpExport({signal,body},{headers:{"x-interfere-producer-version":PRODUCER_VERSION}}),consecutiveAuthRejections=0,resultCallback({code:ExportResultCode.SUCCESS})}catch(error){error instanceof InterfereError&&detectUnacceptableExport(error),resultCallback({code:ExportResultCode.FAILED,error:toError(error)})}})()})}var IngestTraceExporter=class{send;constructor(send){this.send=send}export(spans,resultCallback){if(spans.length===0){resultCallback({code:ExportResultCode.SUCCESS});return}sendInKeepaliveChunks(spans,chunk=>JsonTraceSerializer.serializeRequest(chunk),this.send,resultCallback)}async shutdown(){return Promise.resolve()}async forceFlush(){return Promise.resolve()}};function createTraceExporter(input){return new IngestTraceExporter(makeSender(input,`traces`))}function createMetricExporter(input,gatedResourceAttributes){return new IngestMetricExporter(makeSender(input,`metrics`),gatedResourceAttributes)}function createLogExporter(input){return new IngestLogExporter(makeSender(input,`logs`))}export{isIngestHalted as a,createTraceExporter as i,createLogExporter as n,resetIngestHalt as o,createMetricExporter as r,INGEST_IGNORE_RE as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as sendInKeepaliveChunks}from"./keepalive-chunks-BZv3PhHT.mjs";import{ExportResultCode}from"@opentelemetry/core";import{JsonLogsSerializer}from"@opentelemetry/otlp-transformer";var IngestLogExporter=class{send;constructor(send){this.send=send}export(logs,resultCallback){if(logs.length===0){resultCallback({code:ExportResultCode.SUCCESS});return}sendInKeepaliveChunks(logs,chunk=>JsonLogsSerializer.serializeRequest(chunk),this.send,resultCallback)}async shutdown(){return Promise.resolve()}async forceFlush(){return Promise.resolve()}};export{IngestLogExporter as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as ingestQueueAnswerSchema,t as INGEST_QUEUE_QUERY}from"./sw-queue-protocol-DnTSOWxy.mjs";let consecutiveFailures=0,blockedUntil=0,queueState=null;function resetIngestBackoff(){consecutiveFailures=0,blockedUntil=0,queueState=null}var IngestBackoffError=class extends Error{constructor(){super(`Interfere ingest is backing off after a network failure; request not sent`),this.name=`IngestBackoffError`}};function noteNetworkFailure(){Date.now()<blockedUntil||(consecutiveFailures+=1,blockedUntil=Date.now()+Math.min(5e3*2**(consecutiveFailures-1),6e5))}function absoluteUrl(input){try{return new URL(input instanceof Request?input.url:String(input),globalThis.location.href).href}catch{return null}}function currentController(){try{return`serviceWorker`in navigator?navigator.serviceWorker.controller:null}catch{return null}}async function askIngestQueue(state,url){let{promise,resolve}=Promise.withResolvers(),channel=new MessageChannel;channel.port1.addEventListener(`message`,event=>{let answer=ingestQueueAnswerSchema.safeParse(event.data);state.responsive=!0,resolve(answer.success&&answer.data.accepted),channel.port1.close()}),channel.port1.start();let query={type:INGEST_QUEUE_QUERY,url};try{state.controller.postMessage(query,[channel.port2])}catch{channel.port1.close(),resolve(!1)}return promise}function queryIngestQueue(input,controller){let url=absoluteUrl(input);if(!controller||url===null)return null;queueState?.controller!==controller&&(queueState={answers:new Map,controller,responsive:!1});let state=queueState,answer=state.answers.get(url);return!answer&&state.answers.size<32&&(answer=askIngestQueue(state,url),state.answers.set(url,answer)),answer?{answer,state}:null}async function ingestQueueAccepts(query){if(!query?.state.responsive)return!1;let timer,timeout=new Promise(resolve=>{timer=setTimeout(()=>{resolve(!1)},1e3)});try{return await Promise.race([query.answer,timeout])}finally{clearTimeout(timer)}}async function fetchIngest(url,send,controller=currentController()){let query=queryIngestQueue(url,controller),viaQueue=!1;if(Date.now()<blockedUntil&&(viaQueue=await ingestQueueAccepts(query),!viaQueue))throw new IngestBackoffError;let response;try{response=await send()}catch(error){throw error instanceof TypeError&¬eNetworkFailure(),error}return viaQueue||(consecutiveFailures=0,blockedUntil=0),response}export{fetchIngest as n,resetIngestBackoff as r,IngestBackoffError as t};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as InterfereContextValue, i as InterfereContext } from "../../provider-
|
|
1
|
+
import { a as InterfereContextValue, i as InterfereContext } from "../../provider-BMMGZWyS.mjs";
|
|
2
2
|
import { Component, ContextType, ReactNode } from "react";
|
|
3
3
|
//#region src/internal/capture/capture-boundary.d.ts
|
|
4
4
|
interface CaptureBoundaryProps {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { n as IngestQueueController } from "../../sw-queue-protocol-DqP1EQtQ.mjs";
|
|
1
2
|
//#region src/internal/ingest-backoff/ingest-backoff.d.ts
|
|
2
3
|
/** Test-only reset of the ingest network backoff. */
|
|
3
4
|
export declare function resetIngestBackoff(): void;
|
|
@@ -6,7 +7,7 @@ export declare class IngestBackoffError extends Error {
|
|
|
6
7
|
constructor();
|
|
7
8
|
}
|
|
8
9
|
/**
|
|
9
|
-
* Sends one ingest request unless an earlier network failure is still backing off. A fetch rejection with a `TypeError` (no HTTP response: blocked, offline or unreachable) pauses every ingest request on the page for 5 s, doubling per consecutive failure up to 10 minutes. Any HTTP response clears the backoff.
|
|
10
|
+
* Sends one ingest request to `url` unless an earlier network failure is still backing off. A fetch rejection with a `TypeError` (no HTTP response: blocked, offline or unreachable) pauses every ingest request on the page for 5 s, doubling per consecutive failure up to 10 minutes. Any HTTP response clears the backoff. During a pause, a request still goes out when the page's controlling service worker runs `installIngestQueue` and confirms it queues `url`, because that worker answers a network failure with a queued 202 instead of a page-visible error. `controller` defaults to the page's controlling service worker.
|
|
10
11
|
*/
|
|
11
|
-
export declare function fetchIngest(send: () => Promise<Response
|
|
12
|
+
export declare function fetchIngest(url: RequestInfo | URL, send: () => Promise<Response>, controller?: IngestQueueController | null): Promise<Response>;
|
|
12
13
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as fetchIngest,r as resetIngestBackoff,t as IngestBackoffError}from"../../ingest-backoff-
|
|
1
|
+
import{n as fetchIngest,r as resetIngestBackoff,t as IngestBackoffError}from"../../ingest-backoff-BdBT-jss.mjs";export{IngestBackoffError,fetchIngest,resetIngestBackoff};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { s as Kernel } from "../provider-
|
|
1
|
+
import { s as Kernel } from "../provider-BMMGZWyS.mjs";
|
|
2
2
|
//#region src/internal/kernel-registry.d.ts
|
|
3
3
|
export declare function registerKernel(kernel: Kernel): void;
|
|
4
4
|
export declare function unregisterKernel(kernel: Kernel): void;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { r as PrivacyOptions } from "../privacy-CPKosXDP.mjs";
|
|
2
|
-
import { _ as readReleaseSlugFromGlobals, c as KernelConsent, d as KernelInternalOptions, f as KernelOptions, g as createKernel, h as buildSdkStack, l as KernelDevice, m as TracingOptions, p as KernelSession, s as Kernel, u as KernelIdentity } from "../provider-
|
|
2
|
+
import { _ as readReleaseSlugFromGlobals, c as KernelConsent, d as KernelInternalOptions, f as KernelOptions, g as createKernel, h as buildSdkStack, l as KernelDevice, m as TracingOptions, p as KernelSession, s as Kernel, u as KernelIdentity } from "../provider-BMMGZWyS.mjs";
|
|
3
3
|
import { i as HttpStatusCodeRange, n as CaptureFailedRequestsOption, r as CaptureFailedRequestsOptions } from "../instrumentations-S-BCpguB.mjs";
|
|
4
4
|
import { t as RecordExceptionOpts } from "../exception-span-zN1tvBdh.mjs";
|
|
5
5
|
import { t as isEnabledByEnvironment } from "../environment-CtCFKD2N.mjs";
|
package/dist/internal/kernel.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as isEnabledByEnvironment}from"../environment-CoEXhF1a.mjs";import{i as readReleaseSlugFromGlobals,n as buildSdkStack,r as createKernel,t as Kernel}from"../kernel-
|
|
1
|
+
import{t as isEnabledByEnvironment}from"../environment-CoEXhF1a.mjs";import{i as readReleaseSlugFromGlobals,n as buildSdkStack,r as createKernel,t as Kernel}from"../kernel-zu11DwyQ.mjs";export{Kernel,buildSdkStack,createKernel,isEnabledByEnvironment,readReleaseSlugFromGlobals};
|
|
@@ -2,8 +2,8 @@ import { ReadableSpan, SpanProcessor } from "@opentelemetry/sdk-trace-base";
|
|
|
2
2
|
//#region src/internal/otel/export-filter.d.ts
|
|
3
3
|
/** Whether a finished span is worth exporting. Long tasks under 500 ms are dropped. */
|
|
4
4
|
export declare function shouldExportSpan(span: ReadableSpan): boolean;
|
|
5
|
-
/** Forwards only exportable spans to the wrapped export processor,
|
|
6
|
-
export declare function createExportFilterProcessor(next: SpanProcessor): {
|
|
5
|
+
/** Forwards only exportable spans to the wrapped export processor, flushes it as soon as a span carrying an exception is queued, and reports that span to `onExceptionSpan`. */
|
|
6
|
+
export declare function createExportFilterProcessor(next: SpanProcessor, onExceptionSpan?: () => void): {
|
|
7
7
|
onStart: (span: import("@opentelemetry/sdk-trace-base").Span, parentContext: import("@opentelemetry/api").Context) => void;
|
|
8
8
|
onEnd: (span: ReadableSpan) => void;
|
|
9
9
|
forceFlush: () => Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as shouldExportSpan,t as createExportFilterProcessor}from"../../export-filter-
|
|
1
|
+
import{n as shouldExportSpan,t as createExportFilterProcessor}from"../../export-filter-CnyAaPct.mjs";export{createExportFilterProcessor,shouldExportSpan};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as IngestLogExporter}from"../../exporter-logs-
|
|
1
|
+
import{t as IngestLogExporter}from"../../exporter-logs-BbzSiQJi.mjs";export{IngestLogExporter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as isIngestHalted,i as createTraceExporter,n as createLogExporter,o as resetIngestHalt,r as createMetricExporter,t as INGEST_IGNORE_RE}from"../../exporter-
|
|
1
|
+
import{a as isIngestHalted,i as createTraceExporter,n as createLogExporter,o as resetIngestHalt,r as createMetricExporter,t as INGEST_IGNORE_RE}from"../../exporter-CCgTznZ0.mjs";export{INGEST_IGNORE_RE,createLogExporter,createMetricExporter,createTraceExporter,isIngestHalted,resetIngestHalt};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { a as InstrumentationsInput, i as HttpStatusCodeRange, n as CaptureFailedRequestsOption, o as registerBundledInstrumentations, r as CaptureFailedRequestsOptions, t as BundledInstrumentations } from "../../instrumentations-S-BCpguB.mjs";
|
|
2
2
|
import { a as seedPageScope, i as installNavigationScope, n as PAGE_SCOPE_MAX_AGE_MS, r as createPageScopeRotator, t as NavigationScopeInput } from "../../navigation-CkiV6lJY.mjs";
|
|
3
3
|
import { t as readPropagationFromDocument } from "../../propagation-CssinKCy.mjs";
|
|
4
|
-
import { n as OtelProviderInput, r as buildOtelProvider, t as OtelProviderHandle } from "../../provider-
|
|
4
|
+
import { n as OtelProviderInput, r as buildOtelProvider, t as OtelProviderHandle } from "../../provider-Dy0mVCx5.mjs";
|
|
5
5
|
import { n as captureWebVitals } from "../../web-vitals-x8y70B5x.mjs";
|
|
6
|
-
import "../../index-
|
|
6
|
+
import "../../index-CPrYhbZR.mjs";
|
|
7
7
|
export { type BundledInstrumentations, type CaptureFailedRequestsOption, type CaptureFailedRequestsOptions, type HttpStatusCodeRange, type InstrumentationsInput, type NavigationScopeInput, type OtelProviderHandle, type OtelProviderInput, PAGE_SCOPE_MAX_AGE_MS, buildOtelProvider, captureWebVitals, createPageScopeRotator, installNavigationScope, readPropagationFromDocument, registerBundledInstrumentations, seedPageScope };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as registerBundledInstrumentations}from"../../instrumentations-NN81kslu.mjs";import{i as seedPageScope,n as createPageScopeRotator,r as installNavigationScope,t as PAGE_SCOPE_MAX_AGE_MS}from"../../navigation-DwkvuhFR.mjs";import{t as readPropagationFromDocument}from"../../propagation-DVcqCu_E.mjs";import{t as buildOtelProvider}from"../../provider-
|
|
1
|
+
import{t as registerBundledInstrumentations}from"../../instrumentations-NN81kslu.mjs";import{i as seedPageScope,n as createPageScopeRotator,r as installNavigationScope,t as PAGE_SCOPE_MAX_AGE_MS}from"../../navigation-DwkvuhFR.mjs";import{t as readPropagationFromDocument}from"../../propagation-DVcqCu_E.mjs";import{t as buildOtelProvider}from"../../provider-DwCQ_vj0.mjs";import{t as captureWebVitals}from"../../web-vitals-CxXDUgpl.mjs";export{PAGE_SCOPE_MAX_AGE_MS,buildOtelProvider,captureWebVitals,createPageScopeRotator,installNavigationScope,readPropagationFromDocument,registerBundledInstrumentations,seedPageScope};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { r as SignalSender } from "../../exporter-logs-DMr5-1Yi.mjs";
|
|
2
|
+
import { ExportResult } from "@opentelemetry/core";
|
|
3
|
+
//#region src/internal/otel/keepalive-chunks.d.ts
|
|
4
|
+
/** Sends `items` as one request, or as keepalive-sized requests while the page is hidden, and reports one result: the first failure, else success. */
|
|
5
|
+
export declare function sendInKeepaliveChunks<T>(items: T[], serialize: (items: T[]) => Uint8Array | undefined, send: SignalSender, resultCallback: (result: ExportResult) => void): void;
|
|
6
|
+
//#endregion
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as sendInKeepaliveChunks}from"../../keepalive-chunks-BZv3PhHT.mjs";export{sendInKeepaliveChunks};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as PageScopeRotator, t as PageScopeContextManager } from "../../page-scope-context-manager-
|
|
1
|
+
import { n as PageScopeRotator, t as PageScopeContextManager } from "../../page-scope-context-manager-DUhBvuAz.mjs";
|
|
2
2
|
export { PageScopeContextManager, PageScopeRotator };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as PageScopeContextManager}from"../../page-scope-context-manager-
|
|
1
|
+
import{t as PageScopeContextManager}from"../../page-scope-context-manager-Bs-m4fv7.mjs";export{PageScopeContextManager};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as OtelProviderInput, r as buildOtelProvider, t as OtelProviderHandle } from "../../provider-
|
|
1
|
+
import { n as OtelProviderInput, r as buildOtelProvider, t as OtelProviderHandle } from "../../provider-Dy0mVCx5.mjs";
|
|
2
2
|
export { OtelProviderHandle, OtelProviderInput, buildOtelProvider };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as buildOtelProvider}from"../../provider-
|
|
1
|
+
import{t as buildOtelProvider}from"../../provider-DwCQ_vj0.mjs";export{buildOtelProvider};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
//#region src/internal/page-lifecycle/keepalive-budget.d.ts
|
|
2
2
|
/**
|
|
3
|
-
* Reserves keepalive budget for one request body. Returns the release callback when the
|
|
3
|
+
* Reserves keepalive budget for one request body. Returns the release callback when the page's in-flight keepalive bodies stay within `limit` (the shared budget by default), or null when the request must go out without keepalive.
|
|
4
4
|
*/
|
|
5
|
-
export declare function reserveKeepaliveBody(bytes: number): (() => void) | null;
|
|
5
|
+
export declare function reserveKeepaliveBody(bytes: number, limit?: number): (() => void) | null;
|
|
6
6
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as reserveKeepaliveBody}from"../../keepalive-budget-
|
|
1
|
+
import{t as reserveKeepaliveBody}from"../../keepalive-budget-BfoHXD04.mjs";export{reserveKeepaliveBody};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { v as PluginRuntime } from "../../provider-
|
|
1
|
+
import { v as PluginRuntime } from "../../provider-BMMGZWyS.mjs";
|
|
2
2
|
export { PluginRuntime };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as PluginRuntime}from"../../plugin-runtime-
|
|
1
|
+
import{t as PluginRuntime}from"../../plugin-runtime-DgB1_Xc5.mjs";export{PluginRuntime};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as InterfereContextValue, i as InterfereContext, o as NULL_CONTEXT_VALUE } from "../provider-
|
|
1
|
+
import { a as InterfereContextValue, i as InterfereContext, o as NULL_CONTEXT_VALUE } from "../provider-BMMGZWyS.mjs";
|
|
2
2
|
export { InterfereContext, InterfereContextValue, NULL_CONTEXT_VALUE };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as primeReactDomKeys}from"../react-dom-keys-BIJuLkQR.mjs";export{primeReactDomKeys};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as ingestQueueAnswerSchema, i as answerIngestQueueQuery, n as IngestQueueController, o as ingestQueueQuerySchema, r as IngestQueueQuery, t as INGEST_QUEUE_QUERY } from "../sw-queue-protocol-DqP1EQtQ.mjs";
|
|
2
|
+
export { INGEST_QUEUE_QUERY, IngestQueueController, IngestQueueQuery, answerIngestQueueQuery, ingestQueueAnswerSchema, ingestQueueQuerySchema };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as ingestQueueQuerySchema,n as answerIngestQueueQuery,r as ingestQueueAnswerSchema,t as INGEST_QUEUE_QUERY}from"../sw-queue-protocol-DnTSOWxy.mjs";export{INGEST_QUEUE_QUERY,answerIngestQueueQuery,ingestQueueAnswerSchema,ingestQueueQuerySchema};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isRetryableStatus}from"@interfere/helpers/retry-request";import{Queue}from"workbox-background-sync";const SYNTHETIC_QUEUED_RESPONSE={status:202,statusText:`Queued`};async function postToClients(message){let clients=await self.clients.matchAll({includeUncontrolled:!1});for(let client of clients)client.postMessage(message)}async function totalQueueBytes(queue){let entries=await queue.getAll(),total=0;for(let entry of entries){let meta=entry.metadata;meta&&`bytes`in meta&&typeof meta.bytes==`number`&&(total+=meta.bytes)}return total}async function pruneOldest(queue,neededBytes){let total=await totalQueueBytes(queue);for(;total+neededBytes>10485760;){let dropped=await queue.shiftRequest();if(!dropped)break;let meta=dropped.metadata;meta&&`bytes`in meta&&typeof meta.bytes==`number`&&(total-=meta.bytes),await postToClients({reason:`queue_size_cap`,type:`interfere.sw.dropped`,url:dropped.request.url})}}async function enqueue(queue,request){let cloned=request.clone(),bytes=(await cloned.clone().arrayBuffer()).byteLength;await pruneOldest(queue,bytes),await queue.pushRequest({metadata:{bytes},request:cloned}),await postToClients({type:`interfere.sw.queued`,url:request.url})}function installIngestQueue(options={}){let matches=options.match??(url=>url.pathname.startsWith(`/api/interfere/`)),replayInFlight,replay=async q=>{replayInFlight??=(async()=>{try{let entry=await q.shiftRequest();for(;entry;){try{let res=await self.fetch(entry.request.clone());if(!res.ok&&isRetryableStatus(res.status))throw Error(`retry status ${res.status}`);await postToClients({type:`interfere.sw.replayed`,url:entry.request.url})}catch(error){throw await q.unshiftRequest(entry),error}entry=await q.shiftRequest()}}finally{replayInFlight=void 0}})(),await replayInFlight},queue=new Queue(options.queueName??`interfere-ingest`,{maxRetentionTime:1440,onSync:async({queue:q})=>{await replay(q)}});self.addEventListener(`activate`,event=>{event.waitUntil(replay(queue).catch(()=>{}))}),self.addEventListener(`fetch`,event=>{let{request}=event;if(request.method!==`POST`)return;let url;try{url=new URL(request.url)}catch{return}matches(url,request)&&event.respondWith((async()=>{try{let res=await self.fetch(request.clone());return res.ok?res:isRetryableStatus(res.status)?(await enqueue(queue,request),new Response(null,SYNTHETIC_QUEUED_RESPONSE)):res}catch{return await enqueue(queue,request),new Response(null,SYNTHETIC_QUEUED_RESPONSE)}})())})}export{installIngestQueue};
|
|
1
|
+
import{i as ingestQueueQuerySchema,n as answerIngestQueueQuery}from"../sw-queue-protocol-DnTSOWxy.mjs";import{isRetryableStatus}from"@interfere/helpers/retry-request";import{Queue}from"workbox-background-sync";const SYNTHETIC_QUEUED_RESPONSE={status:202,statusText:`Queued`};async function postToClients(message){let clients=await self.clients.matchAll({includeUncontrolled:!1});for(let client of clients)client.postMessage(message)}async function totalQueueBytes(queue){let entries=await queue.getAll(),total=0;for(let entry of entries){let meta=entry.metadata;meta&&`bytes`in meta&&typeof meta.bytes==`number`&&(total+=meta.bytes)}return total}async function pruneOldest(queue,neededBytes){let total=await totalQueueBytes(queue);for(;total+neededBytes>10485760;){let dropped=await queue.shiftRequest();if(!dropped)break;let meta=dropped.metadata;meta&&`bytes`in meta&&typeof meta.bytes==`number`&&(total-=meta.bytes),await postToClients({reason:`queue_size_cap`,type:`interfere.sw.dropped`,url:dropped.request.url})}}async function enqueue(queue,request){let cloned=request.clone(),bytes=(await cloned.clone().arrayBuffer()).byteLength;await pruneOldest(queue,bytes),await queue.pushRequest({metadata:{bytes},request:cloned}),await postToClients({type:`interfere.sw.queued`,url:request.url})}function installIngestQueue(options={}){let matches=options.match??(url=>url.pathname.startsWith(`/api/interfere/`)),replayInFlight,replay=async q=>{replayInFlight??=(async()=>{try{let entry=await q.shiftRequest();for(;entry;){try{let res=await self.fetch(entry.request.clone());if(!res.ok&&isRetryableStatus(res.status))throw Error(`retry status ${res.status}`);await postToClients({type:`interfere.sw.replayed`,url:entry.request.url})}catch(error){throw await q.unshiftRequest(entry),error}entry=await q.shiftRequest()}}finally{replayInFlight=void 0}})(),await replayInFlight},queue=new Queue(options.queueName??`interfere-ingest`,{maxRetentionTime:1440,onSync:async({queue:q})=>{await replay(q)}});self.addEventListener(`activate`,event=>{event.waitUntil(replay(queue).catch(()=>{}))}),self.addEventListener(`message`,event=>{let[port]=event.ports,query=ingestQueueQuerySchema.safeParse(event.data);port&&query.success&&answerIngestQueueQuery(query.data,port,matches)}),self.addEventListener(`fetch`,event=>{let{request}=event;if(request.method!==`POST`)return;let url;try{url=new URL(request.url)}catch{return}matches(url,request)&&event.respondWith((async()=>{try{let res=await self.fetch(request.clone());return res.ok?res:isRetryableStatus(res.status)?(await enqueue(queue,request),new Response(null,SYNTHETIC_QUEUED_RESPONSE)):res}catch{return await enqueue(queue,request),new Response(null,SYNTHETIC_QUEUED_RESPONSE)}})())})}export{installIngestQueue};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as SDK_NAME,r as SDK_VERSION,t as PRODUCER_VERSION}from"../version-
|
|
1
|
+
import{n as SDK_NAME,r as SDK_VERSION,t as PRODUCER_VERSION}from"../version-CtEAnX65.mjs";export{PRODUCER_VERSION,SDK_NAME,SDK_VERSION};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { f as KernelOptions, s as Kernel } from "../provider-
|
|
1
|
+
import { f as KernelOptions, s as Kernel } from "../provider-BMMGZWyS.mjs";
|
|
2
2
|
import { ConsentInput, ConsentState } from "@interfere/types/sdk/plugins/manifest";
|
|
3
3
|
import { IdentifyParams } from "@interfere/types/sdk/identify";
|
|
4
4
|
//#region src/internal/wrapper-singleton.d.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as createLogger}from"../log-D6Ht--tv.mjs";import{n as registerKernel,r as unregisterKernel}from"../kernel-registry-6f-3VCIy.mjs";import{n as isForceEnableActive,t as hasPublicKey}from"../config-VOyDjqS7.mjs";import{t as isEnabledByEnvironment}from"../environment-CoEXhF1a.mjs";import{r as createKernel}from"../kernel-
|
|
1
|
+
import{t as createLogger}from"../log-D6Ht--tv.mjs";import{n as registerKernel,r as unregisterKernel}from"../kernel-registry-6f-3VCIy.mjs";import{n as isForceEnableActive,t as hasPublicKey}from"../config-VOyDjqS7.mjs";import{t as isEnabledByEnvironment}from"../environment-CoEXhF1a.mjs";import{r as createKernel}from"../kernel-zu11DwyQ.mjs";import{t as primeReactDomKeys}from"../react-dom-keys-BIJuLkQR.mjs";import{n as isBotUserAgent}from"../bot-YLSbnCeg.mjs";const log=createLogger(`init`);function createWrapperSingleton(input){let kernel=null,pending=null,queuedConsent=null,queuedIdentity=null,listeners=new Set;function emit(){for(let listener of listeners)listener()}async function initKernel(internalOpts){try{let k=await createKernel({opts:internalOpts});return kernel=k,registerKernel(k),queuedConsent&&=(k.consent.set(queuedConsent.value),null),queuedIdentity&&=(k.identity.set(queuedIdentity),null),emit(),k}finally{pending=null}}return{async close(){if(!kernel)return;let previous=kernel;await previous.dispose(),kernel=null,unregisterKernel(previous),emit()},consent:{get:()=>kernel?.consent.get()??null,set:value=>{kernel?kernel.consent.set(value):queuedConsent={value}}},getKernel(){if(!kernel)throw Error(`Interfere SDK not initialized. Call init() from your ${input.initEntryName} entrypoint.`);return kernel},getKernelOrNull(){return kernel},identity:{clear:()=>{queuedIdentity=null,kernel?.identity.clear()},get:()=>kernel?.identity.get()??queuedIdentity,set:async params=>{if(kernel)return kernel.identity.set(params);queuedIdentity=params}},async init(opts={}){if(kernel)return kernel;if(pending)return pending;if(!(opts.enabled??isEnabledByEnvironment())||!isForceEnableActive()&&isBotUserAgent())return null;if(!hasPublicKey())return log.warn(`No public key is configured, so the SDK is disabled. Set INTERFERE_PUBLIC_KEY (VITE_INTERFERE_PUBLIC_KEY for Vite) on builds that should send telemetry.`),null;let internalOpts={...opts,_wrapperVersions:[input.producerVersion]};return primeReactDomKeys(),pending=initKernel(internalOpts),pending},subscribeToKernel(listener){return listeners.add(listener),(()=>{listeners.delete(listener)})}}}export{createWrapperSingleton};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const KEEPALIVE_BODY_BUDGET_BYTES=6e4;let keepaliveBodyBytes=0;function reserveKeepaliveBody(bytes,limit=KEEPALIVE_BODY_BUDGET_BYTES){if(keepaliveBodyBytes+bytes>Math.min(limit,KEEPALIVE_BODY_BUDGET_BYTES))return null;keepaliveBodyBytes+=bytes;let released=!1;return(()=>{released||(released=!0,keepaliveBodyBytes-=bytes)})}export{reserveKeepaliveBody as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as isPageHidden}from"./page-lifecycle-rJEJNdKj.mjs";import{ExportResultCode}from"@opentelemetry/core";function splitForKeepalive(items,serialize){let chunks=[],pending=[items];for(let next=pending.pop();next;next=pending.pop()){if(next.length<=1||(serialize(next)?.byteLength??0)<=16e3){chunks.push(next);continue}let middle=Math.ceil(next.length/2);pending.push(next.slice(middle),next.slice(0,middle))}return chunks}function sendInKeepaliveChunks(items,serialize,send,resultCallback){let chunks=isPageHidden()?splitForKeepalive(items,serialize):[items];if(chunks.length===1){send(serialize(items),resultCallback);return}let pending=chunks.length,failure,settle=result=>{result.code!==ExportResultCode.SUCCESS&&(failure??=result),--pending,pending===0&&resultCallback(failure??{code:ExportResultCode.SUCCESS})};for(let chunk of chunks)send(serialize(chunk),settle)}export{sendInKeepaliveChunks as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as createLogger}from"./log-D6Ht--tv.mjs";import{i as onPageUnloading,n as onPageHidden}from"./page-lifecycle-rJEJNdKj.mjs";import{t as SessionTracker}from"./api-C8aG7li1.mjs";import{n as getStringGlobal,t as getGlobal}from"./global-DYq1Z4_H.mjs";import{i as setIngestHost,r as resolveTargets}from"./config-VOyDjqS7.mjs";import{a as resolvePrivacyPolicy}from"./privacy-CRuL0X8r.mjs";import{t as PRODUCER_VERSION}from"./version-CtEAnX65.mjs";import{t as INGEST_IGNORE_RE}from"./exporter-CCgTznZ0.mjs";import{t as recordInitialNavigation}from"./initial-navigation-YeK6UUHX.mjs";import{n as recordExceptionOnSpan,r as startExceptionSpan,t as buildExceptionEventAttrs}from"./exception-span-B74fhBQb.mjs";import{t as PluginRuntime}from"./plugin-runtime-DgB1_Xc5.mjs";import{isNonErrorException,shouldDropBrowserExtensionNoise,shouldDropUnresolvableStack}from"@interfere/types/sdk/errors";import{trace}from"@opentelemetry/api";import{omitUndefined}from"@interfere/helpers/omit-undefined";import{InterfereClient}from"@interfere/javascript";import{releaseSlugSchema}from"@interfere/types/releases/slug";import{FORCE_ENABLE_GLOBAL,RELEASE_SLUG_GLOBAL,SDK_STACK_GLOBAL}from"@interfere/types/sdk/injected-globals";import{readBakedPlugins,remoteConfigInputSchema}from"@interfere/types/sdk/remote-config";import{SERVICE_NAME_GLOBAL}from"@interfere/types/sdk/service-name";import{redactUrl,resolveUrlRedaction}from"@interfere/types/sdk/url-redaction";const log=createLogger(`kernel`),REPLAY_UPLOAD_RE=/\/v3\/replay\/upload\//u;function buildSdkStack(wrapperVersions){return[...wrapperVersions??[],PRODUCER_VERSION]}var Kernel=class{consent;identity;device;session;privacyPolicy;urlRedaction;redactUrl=url=>redactUrl(url,this.urlRedaction);seen=new WeakSet;initialNavigationSeen=new Set;runtime=null;otel=null;otelDispose=null;otelControls=null;deviceInfoCaptureEnabled=!1;unsubscribePageHidden=null;unsubscribePageUnloading=null;tracker;constructor(tracker,privacy={}){this.tracker=tracker,this.privacyPolicy=resolvePrivacyPolicy(privacy),this.urlRedaction=resolveUrlRedaction(privacy.urls),this.consent={get:()=>this.requireRuntime().getConsent(),set:value=>{let runtime=this.requireRuntime();value===void 0?runtime.resetConsent():runtime.setConsent(value)}},this.identity={clear:()=>{this.tracker.reset()},get:()=>this.tracker.getIdentity(),set:async params=>this.tracker.identify(params)},this.device={getDeviceId:()=>this.tracker.getDeviceId(),getFpHash:()=>this.tracker.getFpHash()},this.session={getId:()=>this.tracker.sessionId(),getWindowId:()=>this.tracker.windowId()},this.unsubscribePageHidden=onPageHidden(()=>{this.flush().catch(()=>{})}),this.unsubscribePageUnloading=onPageUnloading(()=>{this.flush().catch(()=>{})})}attachRuntime(runtime){this.runtime=runtime}requireRuntime(){if(!this.runtime)throw Error(`Kernel runtime not attached. createKernel must call attachRuntime before any consent/dispose path runs.`);return this.runtime}getSessionId(){return this.tracker.sessionId()??``}getWindowId(){return this.tracker.windowId()??``}onSessionPause(handler){return this.tracker.onSessionPause(handler)}onSessionExceptionWhilePaused(handler){return this.tracker.onSessionExceptionWhilePaused(handler)}noteException(){this.tracker.noteException()}onSessionResume(handler){return this.tracker.onSessionResume(handler)}getPluginConfigState(key){return this.requireRuntime().getPluginConfigState(key)}getReplayConfig(){return this.requireRuntime().getReplayConfig()}isInteractionCaptureEnabled(){return this.requireRuntime().isInteractionCaptureEnabled()}subscribePluginConfigState(key,listener){return this.requireRuntime().subscribePluginConfigState(key,listener)}getTracer(name){return this.otel?.tracerProvider.getTracer(name)??trace.getTracer(name)}startPageEventsCapture(){let{otelControls:controls,otel}=this;return!controls||!otel?null:(controls.setPageEventsEnabled(!0),this.recordInitialNavigation(otel.loggerProvider),(()=>{controls.setPageEventsEnabled(!1)}))}startDeviceInfoCapture(){return this.tracker.startDeviceIdentity(),this.deviceInfoCaptureEnabled=!0,(reason=>{this.deviceInfoCaptureEnabled=!1,reason===`consent-revoked`&&this.tracker.discardDeviceIdentity()})}isDeviceInfoCaptureEnabled(){return this.deviceInfoCaptureEnabled}recordException(value,opts){if(!isNonErrorException(value)){if(this.seen.has(value))return;this.seen.add(value)}if(!isNonErrorException(value)){let stacks=[],current=value;for(let depth=0;current&&depth<5;depth+=1)current.stack&&stacks.push(current.stack),current=current.cause instanceof Error?current.cause:void 0;if(shouldDropBrowserExtensionNoise(stacks)||shouldDropUnresolvableStack(stacks))return}this.tracker.noteException();let attrs=buildExceptionEventAttrs(value,opts),active=trace.getActiveSpan();if(active?.isRecording()){recordExceptionOnSpan(active,value,attrs,opts.mechanism.handled);return}let tracer=this.otel?.tracerProvider.getTracer(`@interfere/react/exception`);if(!tracer)return;let span=startExceptionSpan(tracer,value);recordExceptionOnSpan(span,value,attrs,opts.mechanism.handled),span.end()}recordLog(input){this.otel&&this.otel.loggerProvider.getLogger(`@interfere/react`).emit(omitUndefined({body:input.body,severityNumber:input.severityNumber,severityText:input.severityText,attributes:input.attributes}))}recordInitialNavigation(loggerProvider){recordInitialNavigation({getSessionId:()=>this.session.getId(),getWindowId:()=>this.session.getWindowId(),loggerProvider,redactUrl:this.redactUrl,seen:this.initialNavigationSeen})}async flush(){this.otel&&await this.otel.flush()}attachOtel(handle,dispose,controls){this.otel=handle,this.otelDispose=dispose,this.otelControls=controls??null}syncProviderConfig(config){this.requireRuntime().applyProviderConfig(config.plugins,config.consent)}async dispose(){this.unsubscribePageHidden?.(),this.unsubscribePageHidden=null,this.unsubscribePageUnloading?.(),this.unsubscribePageUnloading=null,this.runtime&&await this.runtime.dispose(),this.tracker.dispose(),this.otelDispose?.(),this.otelDispose=null,this.otel&&=(await this.otel.shutdown(),null)}};async function createKernel(input={}){let{opts={}}=input,fetcher=opts.fetch??globalThis.fetch.bind(globalThis),remotePlugins=await resolveRemotePlugins(opts,fetcher),targets=resolveTargets(opts.apiHost);log.info(`ingest: %s`,targets.ingest.baseUrl),getGlobal(FORCE_ENABLE_GLOBAL)&&log.warn(`FORCE_ENABLE is active. Events will be dropped by production ingest. This should only be set during local development.`);let tracker=new SessionTracker({fetcher,target:targets.ingest});opts._wrapperVersions?.length&&Object.assign(globalThis,{[SDK_STACK_GLOBAL]:opts._wrapperVersions});let kernel=new Kernel(tracker,opts.privacy),runtime=new PluginRuntime(kernel,opts.consent,remotePlugins??{});if(kernel.attachRuntime(runtime),tracker.start(),runtime.start(),opts.tracing!==!1){let resolvedTracing={...typeof opts.tracing==`object`?opts.tracing:void 0},serviceName=opts.serviceName||getStringGlobal(SERVICE_NAME_GLOBAL);serviceName&&(resolvedTracing.serviceName=serviceName),opts.serviceNamespace!==void 0&&(resolvedTracing.serviceNamespace=opts.serviceNamespace),opts._internalAdditionalSpanProcessors&&(resolvedTracing.additionalSpanProcessors=opts._internalAdditionalSpanProcessors),opts._internalAdditionalLogRecordProcessors&&(resolvedTracing.additionalLogRecordProcessors=opts._internalAdditionalLogRecordProcessors),opts._internalAdditionalMetricReaders&&(resolvedTracing.additionalMetricReaders=opts._internalAdditionalMetricReaders),await wireOtel(kernel,targets,opts._wrapperVersions,resolvedTracing)}return remotePlugins?runtime.applyRemoteConfig(remotePlugins):runtime.applyRemoteConfigDefaults(),kernel}async function resolveRemotePlugins(opts,fetcher){let baked=readBakedPlugins();if(baked)return baked;let remoteConfig=await fetchRemoteConfig(resolveTargets(opts.apiHost).config,fetcher);return remoteConfig?.ingestUrl&&setIngestHost(remoteConfig.ingestUrl),remoteConfig?.plugins??null}async function wireOtel(kernel,targets,wrapperVersions,tracing){let{buildOtelProvider,captureWebVitals,createPageScopeRotator,installNavigationScope,PAGE_SCOPE_MAX_AGE_MS,readPropagationFromDocument,registerBundledInstrumentations,seedPageScope}=await import(`./internal/otel/index.mjs`),releaseSlug=readReleaseSlugFromGlobals(),handle=buildOtelProvider(omitUndefined({clientOptions:targets.ingest,getDeviceId:()=>kernel.device.getDeviceId(),getSessionId:()=>kernel.session.getId(),getPropagationSessionId:()=>kernel.consent.get()?.analytics===!1?null:kernel.session.getId(),isDeviceInfoEnabled:()=>kernel.isDeviceInfoCaptureEnabled(),onExceptionSpan:()=>{kernel.noteException()},releaseSlug,sdkStack:buildSdkStack(wrapperVersions),serviceName:tracing.serviceName||void 0,serviceNamespace:tracing.serviceNamespace,additionalSpanProcessors:[...tracing.spanProcessors??[],...tracing.additionalSpanProcessors??[]],additionalLogRecordProcessors:tracing.additionalLogRecordProcessors,additionalMetricReaders:tracing.additionalMetricReaders,urlRedaction:kernel.urlRedaction})),scopeSpanInput=omitUndefined({tracer:handle.tracerProvider.getTracer(`@interfere/react/navigation`),resolveRoute:tracing.resolveRoute}),extracted=readPropagationFromDocument();handle.contextManager.setPageScope(extracted??seedPageScope(scopeSpanInput)),handle.contextManager.setRotation(createPageScopeRotator(scopeSpanInput),PAGE_SCOPE_MAX_AGE_MS);let disposeNavigationScope=installNavigationScope({...scopeSpanInput,setPageScope:ctx=>{handle.contextManager.setPageScope(ctx)}}),instrumentations=registerBundledInstrumentations(omitUndefined({tracerProvider:handle.tracerProvider,loggerProvider:handle.loggerProvider,ignoreUrls:[INGEST_IGNORE_RE,`${targets.config.baseUrl}/v3/config`,`${targets.ingest.baseUrl}/v3/session`,REPLAY_UPLOAD_RE,...tracing.ignoreUrls??[]],apiHosts:tracing.apiHosts,propagateContextUrls:tracing.propagateContextUrls,resolveRoute:tracing.resolveRoute,captureFailedRequests:tracing.captureFailedRequests,redactUrl:kernel.redactUrl,privacyPolicy:kernel.privacyPolicy,isInteractionCaptureEnabled:()=>kernel.isInteractionCaptureEnabled()}));tracing.webVitals!==!1&&captureWebVitals(omitUndefined({flush:async()=>handle.flush(),meter:handle.meterProvider.getMeter(`@interfere/react/web-vitals`),resolveRoute:tracing.resolveRoute})),kernel.attachOtel(handle,()=>{disposeNavigationScope(),instrumentations.dispose()},{setPageEventsEnabled:instrumentations.setPageEventsEnabled})}async function fetchRemoteConfig(configTarget,fetcher){try{let client=new InterfereClient({...configTarget,fetch:Object.assign(async(url,init)=>fetcher(url,{...init,credentials:`omit`}),fetcher)});return remoteConfigInputSchema.parse(await client.config.getSdkConfig())}catch{return log.warn(`remote config fetch failed, using local defaults`),null}}function readReleaseSlugFromGlobals(){let value=getGlobal(RELEASE_SLUG_GLOBAL);return typeof value==`string`?releaseSlugSchema.parse(value):null}export{readReleaseSlugFromGlobals as i,buildSdkStack as n,createKernel as r,Kernel as t};
|