@ingissa/navcore-telemetry 2.1.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.d.mts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -6,4 +6,4 @@ Optional, non-blocking Deployment Intelligence telemetry client for `@ingissa/na
|
|
|
6
6
|
- Never collects GPS coordinates, routes, addresses, or end-user PII.
|
|
7
7
|
- Bounded FIFO queue, deduplication, exponential backoff, zero runtime dependencies.
|
|
8
8
|
|
|
9
|
-
See [SDK Telemetry Integration](
|
|
9
|
+
See [SDK Telemetry Integration](https://github.com/ingissa/navcore-sdk/blob/main/docs/deployment-intelligence/SDK_TELEMETRY_INTEGRATION.md) for usage and privacy details.
|
package/dist/index.d.mts
CHANGED
|
@@ -8,8 +8,8 @@ type UsageEventType = 'route.loaded' | 'route.load_failed' | 'navigation.started
|
|
|
8
8
|
type PerformanceEventType = 'perf.sdk_init' | 'perf.route_load' | 'perf.gps_processing' | 'perf.component_latency';
|
|
9
9
|
type TelemetryEventType = LifecycleEventType | UsageEventType | PerformanceEventType;
|
|
10
10
|
interface TelemetryLicenseMetadata {
|
|
11
|
-
lid
|
|
12
|
-
pid: 'navcore-suite';
|
|
11
|
+
lid?: string;
|
|
12
|
+
pid: 'navcore-suite' | 'navcore-core';
|
|
13
13
|
bid: string;
|
|
14
14
|
}
|
|
15
15
|
interface TelemetryStorageAdapter {
|
|
@@ -34,6 +34,8 @@ interface TelemetryConfig {
|
|
|
34
34
|
|
|
35
35
|
licenseKey?: string;
|
|
36
36
|
|
|
37
|
+
applicationId?: string;
|
|
38
|
+
|
|
37
39
|
licenseMetadata?: TelemetryLicenseMetadata;
|
|
38
40
|
|
|
39
41
|
environment?: TelemetryEnvironment;
|
package/dist/index.d.ts
CHANGED
|
@@ -8,8 +8,8 @@ type UsageEventType = 'route.loaded' | 'route.load_failed' | 'navigation.started
|
|
|
8
8
|
type PerformanceEventType = 'perf.sdk_init' | 'perf.route_load' | 'perf.gps_processing' | 'perf.component_latency';
|
|
9
9
|
type TelemetryEventType = LifecycleEventType | UsageEventType | PerformanceEventType;
|
|
10
10
|
interface TelemetryLicenseMetadata {
|
|
11
|
-
lid
|
|
12
|
-
pid: 'navcore-suite';
|
|
11
|
+
lid?: string;
|
|
12
|
+
pid: 'navcore-suite' | 'navcore-core';
|
|
13
13
|
bid: string;
|
|
14
14
|
}
|
|
15
15
|
interface TelemetryStorageAdapter {
|
|
@@ -34,6 +34,8 @@ interface TelemetryConfig {
|
|
|
34
34
|
|
|
35
35
|
licenseKey?: string;
|
|
36
36
|
|
|
37
|
+
applicationId?: string;
|
|
38
|
+
|
|
37
39
|
licenseMetadata?: TelemetryLicenseMetadata;
|
|
38
40
|
|
|
39
41
|
environment?: TelemetryEnvironment;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var p=new Set(["lat","latitude","lon","lng","longitude","coord","coords","coordinate","coordinates","location","locations","gps","trace","traces","waypoint","waypoints","geometry","route","polyline","origin","destination","address","street","city","postalcode","email","phone","fullname","username","userid","deviceid","advertisingid","idfa","aaid","serial","imei","macaddress","ip","ipaddress","licensekey","token","password","secret"]);function o(i){if(!i)return;let e={};for(let[t,n]of Object.entries(i)){let s=t.toLowerCase().replace(/[^a-z0-9]/g,"");p.has(s)||(typeof n=="string"?e[t.slice(0,64)]=n.slice(0,120):(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t.slice(0,64)]=n));}return Object.keys(e).length>0?e:void 0}var u="navcore_telemetry_queue_v1",d="navcore_telemetry_install_id_v1";function h(){let i=typeof globalThis<"u"?globalThis.crypto:void 0;return i&&typeof i.randomUUID=="function"?i.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return (e==="x"?t:t&3|8).toString(16)})}function f(i){if(typeof Buffer<"u")return Buffer.from(i,"base64").toString("utf8");if(typeof atob=="function")return atob(i);throw new Error("No base64 decoder available")}function c(i){if(!i)return null;try{let[e]=i.split(".");if(!e)return null;let t=JSON.parse(f(e));return typeof t.lid=="string"&&t.lid&&t.pid==="navcore-suite"&&typeof t.bid=="string"&&t.bid?{lid:t.lid,pid:t.pid,bid:t.bid}:null}catch{return null}}function v(){return typeof navigator<"u"&&navigator.product==="ReactNative"?"unknown":typeof process<"u"&&process.versions?.node?"node":typeof window<"u"?"web":"unknown"}var l=class{constructor(e){this.ingestionToken=null;this.tokenExpiresAtMs=0;this.revoked=false;this.queue=[];this.dedupeCache=new Map;this.recentTimestamps=[];this.consecutiveFailures=0;this.nextRetryAtMs=0;this.flushing=false;this.flushTimer=null;this.initialized=false;this.enabled=!!e.enabled,this.endpoint=e.endpoint.replace(/\/+$/,""),this.environment=e.environment??"production",this.platform=e.platform??v(),this.osVersion=e.osVersion,this.sdkVersion=e.sdkVersion??"2.1.0",this.packages=e.packages??{"@ingissa/navcore-core":this.sdkVersion},this.maxQueueSize=Math.max(10,Math.min(e.maxQueueSize??200,1e3)),this.maxBatchSize=Math.max(1,Math.min(e.maxBatchSize??25,100)),this.flushIntervalMs=Math.max(5e3,e.flushIntervalMs??3e4),this.maxEventAgeMs=Math.max(6e4,e.maxEventAgeMs??1440*60*1e3),this.maxRetries=Math.max(1,e.maxRetries??5),this.baseBackoffMs=Math.max(200,e.baseBackoffMs??1e3),this.rateLimitPerMinute=Math.max(5,e.rateLimitPerMinute??60),this.storage=e.storage,this.fetchFn=e.fetchFn??(typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0),this.licenseMeta=e.licenseMetadata??c(e.licenseKey),this.installationId=e.installationId??h();}isEnabled(){return this.enabled&&!this.revoked}getInstallationId(){return this.installationId}getQueueLength(){return this.queue.length}async start(){!this.isEnabled()||this.initialized||(this.initialized=true,await this.restorePersistedState(),this.track({eventType:"sdk.initialized",status:"ok",component:"NavCore",dedupeKey:`init:${this.installationId}`}),this.flushTimer||(this.flushTimer=setInterval(()=>{this.flush();},this.flushIntervalMs),typeof this.flushTimer.unref=="function"&&this.flushTimer.unref()));}track(e){if(!this.isEnabled())return false;let t=Date.now();if(this.recentTimestamps=this.recentTimestamps.filter(s=>t-s<6e4),this.recentTimestamps.length>=this.rateLimitPerMinute)return false;if(e.dedupeKey){let s=this.dedupeCache.get(e.dedupeKey);if(s&&t-s<1e4)return false;if(this.dedupeCache.set(e.dedupeKey,t),this.dedupeCache.size>500){let r=this.dedupeCache.keys().next().value;r&&this.dedupeCache.delete(r);}}for(this.pruneExpired(t);this.queue.length>=this.maxQueueSize;)this.queue.shift();let n={eventId:h(),eventType:e.eventType,timestamp:new Date(t).toISOString(),sdkVersion:this.sdkVersion,platform:this.platform,status:e.status??"ok",durationMs:typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)?Math.max(0,e.durationMs):void 0,errorCode:e.errorCode?.slice(0,64),component:e.component?.slice(0,64),metadata:o(e.metadata),enqueuedAtMs:t};return this.queue.push(n),this.recentTimestamps.push(t),this.persistQueue(),true}async flush(){if(!this.isEnabled()||this.flushing||this.queue.length===0||!this.fetchFn||!this.licenseMeta)return {sent:0,remaining:this.queue.length};let e=Date.now();if(e<this.nextRetryAtMs)return {sent:0,remaining:this.queue.length};if(this.pruneExpired(e),this.queue.length===0)return {sent:0,remaining:0};this.flushing=true;let t=0;try{if((!this.ingestionToken||e>=this.tokenExpiresAtMs-6e4)&&!await this.register())return this.scheduleBackoff(),{sent:0,remaining:this.queue.length};let n=this.queue.slice(0,this.maxBatchSize),s=n.map(({enqueuedAtMs:a,...m})=>m),r=await this.fetchFn(`${this.endpoint}/v1/telemetry/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ingestionToken}`},body:JSON.stringify({events:s})});return r.status===401?(this.ingestionToken=null,this.scheduleBackoff(),{sent:0,remaining:this.queue.length}):r.status===403?(this.revoked=!0,this.queue=[],this.persistQueue(),{sent:0,remaining:0}):r.ok?(this.queue.splice(0,n.length),t=n.length,this.consecutiveFailures=0,this.nextRetryAtMs=0,await this.persistQueue(),{sent:t,remaining:this.queue.length}):(this.scheduleBackoff(),{sent:0,remaining:this.queue.length})}catch{return this.scheduleBackoff(),{sent:0,remaining:this.queue.length}}finally{this.flushing=false;}}async disable(e=true){this.enabled=false,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),e&&(this.queue=[],this.storage?.removeItem?await Promise.resolve(this.storage.removeItem(u)).catch(()=>{}):await this.persistQueue());}async shutdown(){this.isEnabled()&&(this.track({eventType:"sdk.shutdown",status:"ok",component:"NavCore"}),await this.flush()),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.initialized=false;}async register(){if(!this.fetchFn||!this.licenseMeta)return false;try{let e=await this.fetchFn(`${this.endpoint}/v1/telemetry/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({installationId:this.installationId
|
|
1
|
+
'use strict';var p=new Set(["lat","latitude","lon","lng","longitude","coord","coords","coordinate","coordinates","location","locations","gps","trace","traces","waypoint","waypoints","geometry","route","polyline","origin","destination","address","street","city","postalcode","email","phone","fullname","username","userid","deviceid","advertisingid","idfa","aaid","serial","imei","macaddress","ip","ipaddress","licensekey","token","password","secret"]);function o(i){if(!i)return;let e={};for(let[t,n]of Object.entries(i)){let s=t.toLowerCase().replace(/[^a-z0-9]/g,"");p.has(s)||(typeof n=="string"?e[t.slice(0,64)]=n.slice(0,120):(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t.slice(0,64)]=n));}return Object.keys(e).length>0?e:void 0}var u="navcore_telemetry_queue_v1",d="navcore_telemetry_install_id_v1";function h(){let i=typeof globalThis<"u"?globalThis.crypto:void 0;return i&&typeof i.randomUUID=="function"?i.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return (e==="x"?t:t&3|8).toString(16)})}function f(i){if(typeof Buffer<"u")return Buffer.from(i,"base64").toString("utf8");if(typeof atob=="function")return atob(i);throw new Error("No base64 decoder available")}function c(i){if(!i)return null;try{let[e]=i.split(".");if(!e)return null;let t=JSON.parse(f(e));return typeof t.lid=="string"&&t.lid&&t.pid==="navcore-suite"&&typeof t.bid=="string"&&t.bid?{lid:t.lid,pid:t.pid,bid:t.bid}:null}catch{return null}}function v(){return typeof navigator<"u"&&navigator.product==="ReactNative"?"unknown":typeof process<"u"&&process.versions?.node?"node":typeof window<"u"?"web":"unknown"}var l=class{constructor(e){this.ingestionToken=null;this.tokenExpiresAtMs=0;this.revoked=false;this.queue=[];this.dedupeCache=new Map;this.recentTimestamps=[];this.consecutiveFailures=0;this.nextRetryAtMs=0;this.flushing=false;this.flushTimer=null;this.initialized=false;this.enabled=!!e.enabled,this.endpoint=e.endpoint.replace(/\/+$/,""),this.environment=e.environment??"production",this.platform=e.platform??v(),this.osVersion=e.osVersion,this.sdkVersion=e.sdkVersion??"2.1.0",this.packages=e.packages??{"@ingissa/navcore-core":this.sdkVersion},this.maxQueueSize=Math.max(10,Math.min(e.maxQueueSize??200,1e3)),this.maxBatchSize=Math.max(1,Math.min(e.maxBatchSize??25,100)),this.flushIntervalMs=Math.max(5e3,e.flushIntervalMs??3e4),this.maxEventAgeMs=Math.max(6e4,e.maxEventAgeMs??1440*60*1e3),this.maxRetries=Math.max(1,e.maxRetries??5),this.baseBackoffMs=Math.max(200,e.baseBackoffMs??1e3),this.rateLimitPerMinute=Math.max(5,e.rateLimitPerMinute??60),this.storage=e.storage,this.fetchFn=e.fetchFn??(typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0),this.licenseMeta=e.licenseMetadata??c(e.licenseKey)??{pid:"navcore-core",bid:e.applicationId?.trim()||"navcore-core-app"},this.installationId=e.installationId??h();}isEnabled(){return this.enabled&&!this.revoked}getInstallationId(){return this.installationId}getQueueLength(){return this.queue.length}async start(){!this.isEnabled()||this.initialized||(this.initialized=true,await this.restorePersistedState(),this.track({eventType:"sdk.initialized",status:"ok",component:"NavCore",dedupeKey:`init:${this.installationId}`}),this.flushTimer||(this.flushTimer=setInterval(()=>{this.flush();},this.flushIntervalMs),typeof this.flushTimer.unref=="function"&&this.flushTimer.unref()));}track(e){if(!this.isEnabled())return false;let t=Date.now();if(this.recentTimestamps=this.recentTimestamps.filter(s=>t-s<6e4),this.recentTimestamps.length>=this.rateLimitPerMinute)return false;if(e.dedupeKey){let s=this.dedupeCache.get(e.dedupeKey);if(s&&t-s<1e4)return false;if(this.dedupeCache.set(e.dedupeKey,t),this.dedupeCache.size>500){let r=this.dedupeCache.keys().next().value;r&&this.dedupeCache.delete(r);}}for(this.pruneExpired(t);this.queue.length>=this.maxQueueSize;)this.queue.shift();let n={eventId:h(),eventType:e.eventType,timestamp:new Date(t).toISOString(),sdkVersion:this.sdkVersion,platform:this.platform,status:e.status??"ok",durationMs:typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)?Math.max(0,e.durationMs):void 0,errorCode:e.errorCode?.slice(0,64),component:e.component?.slice(0,64),metadata:o(e.metadata),enqueuedAtMs:t};return this.queue.push(n),this.recentTimestamps.push(t),this.persistQueue(),true}async flush(){if(!this.isEnabled()||this.flushing||this.queue.length===0||!this.fetchFn||!this.licenseMeta)return {sent:0,remaining:this.queue.length};let e=Date.now();if(e<this.nextRetryAtMs)return {sent:0,remaining:this.queue.length};if(this.pruneExpired(e),this.queue.length===0)return {sent:0,remaining:0};this.flushing=true;let t=0;try{if((!this.ingestionToken||e>=this.tokenExpiresAtMs-6e4)&&!await this.register())return this.scheduleBackoff(),{sent:0,remaining:this.queue.length};let n=this.queue.slice(0,this.maxBatchSize),s=n.map(({enqueuedAtMs:a,...m})=>m),r=await this.fetchFn(`${this.endpoint}/v1/telemetry/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ingestionToken}`},body:JSON.stringify({events:s})});return r.status===401?(this.ingestionToken=null,this.scheduleBackoff(),{sent:0,remaining:this.queue.length}):r.status===403?(this.revoked=!0,this.queue=[],this.persistQueue(),{sent:0,remaining:0}):r.ok?(this.queue.splice(0,n.length),t=n.length,this.consecutiveFailures=0,this.nextRetryAtMs=0,await this.persistQueue(),{sent:t,remaining:this.queue.length}):(this.scheduleBackoff(),{sent:0,remaining:this.queue.length})}catch{return this.scheduleBackoff(),{sent:0,remaining:this.queue.length}}finally{this.flushing=false;}}async disable(e=true){this.enabled=false,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),e&&(this.queue=[],this.storage?.removeItem?await Promise.resolve(this.storage.removeItem(u)).catch(()=>{}):await this.persistQueue());}async shutdown(){this.isEnabled()&&(this.track({eventType:"sdk.shutdown",status:"ok",component:"NavCore"}),await this.flush()),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.initialized=false;}async register(){if(!this.fetchFn||!this.licenseMeta)return false;try{let e=await this.fetchFn(`${this.endpoint}/v1/telemetry/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({installationId:this.installationId,...this.licenseMeta.lid?{lid:this.licenseMeta.lid}:{},pid:this.licenseMeta.pid,bid:this.licenseMeta.bid,platform:this.platform,osVersion:this.osVersion,sdkVersion:this.sdkVersion,packages:this.packages,environment:this.environment})});if(e.status===403)return this.revoked=!0,!1;if(!e.ok)return !1;let t=await e.json();return t.ingestionToken?(this.ingestionToken=t.ingestionToken,this.tokenExpiresAtMs=t.expiresAt?Date.parse(t.expiresAt):Date.now()+36e5,!0):!1}catch{return false}}scheduleBackoff(){if(this.consecutiveFailures+=1,this.consecutiveFailures>this.maxRetries){let t=Math.max(1,Math.floor(this.queue.length/2));this.queue.splice(0,t),this.consecutiveFailures=0,this.persistQueue();}let e=Math.min(3e5,this.baseBackoffMs*Math.pow(2,this.consecutiveFailures));this.nextRetryAtMs=Date.now()+e;}pruneExpired(e){let t=e-this.maxEventAgeMs;this.queue.length!==0&&(this.queue=this.queue.filter(n=>n.enqueuedAtMs>=t));}async restorePersistedState(){if(this.storage)try{let e=await this.storage.getItem(d);e&&typeof e=="string"?this.installationId=e:await this.storage.setItem(d,this.installationId);let t=await this.storage.getItem(u);if(t){let n=JSON.parse(t);Array.isArray(n)&&(this.queue=n.slice(-this.maxQueueSize),this.pruneExpired(Date.now()));}}catch{}}async persistQueue(){if(this.storage)try{await this.storage.setItem(u,JSON.stringify(this.queue.slice(-this.maxQueueSize)));}catch{}}};function y(i,e){let t=()=>{e.track({eventType:"route.loaded",status:"ok",component:"NavCore"});},n=()=>{e.track({eventType:"navigation.started",status:"ok",component:"NavCore"});},s=()=>{e.track({eventType:"navigation.off_route",status:"warning",component:"OffRouteFSM"});},r=()=>{e.track({eventType:"navigation.rejoined",status:"ok",component:"OffRouteFSM"});},a=()=>{e.track({eventType:"navigation.completed",status:"ok",component:"NavCore"});};return i.on("routeLoaded",t),i.on("navigationStarted",n),i.on("deviation",s),i.on("rejoined",r),i.on("arrival",a),()=>{i.off("routeLoaded",t),i.off("navigationStarted",n),i.off("deviation",s),i.off("rejoined",r),i.off("arrival",a);}}function g(i,e){let t=[i.subscribe("routeLoaded",()=>{e.track({eventType:"route.loaded",status:"ok",component:"NavigationSession"});}),i.subscribe("navigationStarted",()=>{e.track({eventType:"navigation.started",status:"ok",component:"NavigationSession"});}),i.subscribe("deviation",()=>{e.track({eventType:"navigation.off_route",status:"warning",component:"NavigationSession"});}),i.subscribe("rejoined",()=>{e.track({eventType:"navigation.rejoined",status:"ok",component:"NavigationSession"});}),i.subscribe("arrival",()=>{e.track({eventType:"navigation.completed",status:"ok",component:"NavigationSession"});})];return ()=>{for(let n of t)n();}}exports.TelemetryClient=l;exports.attachNavCoreTelemetry=y;exports.attachSessionTelemetry=g;exports.extractLicenseMetadata=c;exports.sanitizeTelemetryMetadata=o;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var p=new Set(["lat","latitude","lon","lng","longitude","coord","coords","coordinate","coordinates","location","locations","gps","trace","traces","waypoint","waypoints","geometry","route","polyline","origin","destination","address","street","city","postalcode","email","phone","fullname","username","userid","deviceid","advertisingid","idfa","aaid","serial","imei","macaddress","ip","ipaddress","licensekey","token","password","secret"]);function o(i){if(!i)return;let e={};for(let[t,n]of Object.entries(i)){let s=t.toLowerCase().replace(/[^a-z0-9]/g,"");p.has(s)||(typeof n=="string"?e[t.slice(0,64)]=n.slice(0,120):(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t.slice(0,64)]=n));}return Object.keys(e).length>0?e:void 0}var u="navcore_telemetry_queue_v1",d="navcore_telemetry_install_id_v1";function h(){let i=typeof globalThis<"u"?globalThis.crypto:void 0;return i&&typeof i.randomUUID=="function"?i.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return (e==="x"?t:t&3|8).toString(16)})}function f(i){if(typeof Buffer<"u")return Buffer.from(i,"base64").toString("utf8");if(typeof atob=="function")return atob(i);throw new Error("No base64 decoder available")}function c(i){if(!i)return null;try{let[e]=i.split(".");if(!e)return null;let t=JSON.parse(f(e));return typeof t.lid=="string"&&t.lid&&t.pid==="navcore-suite"&&typeof t.bid=="string"&&t.bid?{lid:t.lid,pid:t.pid,bid:t.bid}:null}catch{return null}}function v(){return typeof navigator<"u"&&navigator.product==="ReactNative"?"unknown":typeof process<"u"&&process.versions?.node?"node":typeof window<"u"?"web":"unknown"}var l=class{constructor(e){this.ingestionToken=null;this.tokenExpiresAtMs=0;this.revoked=false;this.queue=[];this.dedupeCache=new Map;this.recentTimestamps=[];this.consecutiveFailures=0;this.nextRetryAtMs=0;this.flushing=false;this.flushTimer=null;this.initialized=false;this.enabled=!!e.enabled,this.endpoint=e.endpoint.replace(/\/+$/,""),this.environment=e.environment??"production",this.platform=e.platform??v(),this.osVersion=e.osVersion,this.sdkVersion=e.sdkVersion??"2.1.0",this.packages=e.packages??{"@ingissa/navcore-core":this.sdkVersion},this.maxQueueSize=Math.max(10,Math.min(e.maxQueueSize??200,1e3)),this.maxBatchSize=Math.max(1,Math.min(e.maxBatchSize??25,100)),this.flushIntervalMs=Math.max(5e3,e.flushIntervalMs??3e4),this.maxEventAgeMs=Math.max(6e4,e.maxEventAgeMs??1440*60*1e3),this.maxRetries=Math.max(1,e.maxRetries??5),this.baseBackoffMs=Math.max(200,e.baseBackoffMs??1e3),this.rateLimitPerMinute=Math.max(5,e.rateLimitPerMinute??60),this.storage=e.storage,this.fetchFn=e.fetchFn??(typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0),this.licenseMeta=e.licenseMetadata??c(e.licenseKey),this.installationId=e.installationId??h();}isEnabled(){return this.enabled&&!this.revoked}getInstallationId(){return this.installationId}getQueueLength(){return this.queue.length}async start(){!this.isEnabled()||this.initialized||(this.initialized=true,await this.restorePersistedState(),this.track({eventType:"sdk.initialized",status:"ok",component:"NavCore",dedupeKey:`init:${this.installationId}`}),this.flushTimer||(this.flushTimer=setInterval(()=>{this.flush();},this.flushIntervalMs),typeof this.flushTimer.unref=="function"&&this.flushTimer.unref()));}track(e){if(!this.isEnabled())return false;let t=Date.now();if(this.recentTimestamps=this.recentTimestamps.filter(s=>t-s<6e4),this.recentTimestamps.length>=this.rateLimitPerMinute)return false;if(e.dedupeKey){let s=this.dedupeCache.get(e.dedupeKey);if(s&&t-s<1e4)return false;if(this.dedupeCache.set(e.dedupeKey,t),this.dedupeCache.size>500){let r=this.dedupeCache.keys().next().value;r&&this.dedupeCache.delete(r);}}for(this.pruneExpired(t);this.queue.length>=this.maxQueueSize;)this.queue.shift();let n={eventId:h(),eventType:e.eventType,timestamp:new Date(t).toISOString(),sdkVersion:this.sdkVersion,platform:this.platform,status:e.status??"ok",durationMs:typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)?Math.max(0,e.durationMs):void 0,errorCode:e.errorCode?.slice(0,64),component:e.component?.slice(0,64),metadata:o(e.metadata),enqueuedAtMs:t};return this.queue.push(n),this.recentTimestamps.push(t),this.persistQueue(),true}async flush(){if(!this.isEnabled()||this.flushing||this.queue.length===0||!this.fetchFn||!this.licenseMeta)return {sent:0,remaining:this.queue.length};let e=Date.now();if(e<this.nextRetryAtMs)return {sent:0,remaining:this.queue.length};if(this.pruneExpired(e),this.queue.length===0)return {sent:0,remaining:0};this.flushing=true;let t=0;try{if((!this.ingestionToken||e>=this.tokenExpiresAtMs-6e4)&&!await this.register())return this.scheduleBackoff(),{sent:0,remaining:this.queue.length};let n=this.queue.slice(0,this.maxBatchSize),s=n.map(({enqueuedAtMs:a,...m})=>m),r=await this.fetchFn(`${this.endpoint}/v1/telemetry/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ingestionToken}`},body:JSON.stringify({events:s})});return r.status===401?(this.ingestionToken=null,this.scheduleBackoff(),{sent:0,remaining:this.queue.length}):r.status===403?(this.revoked=!0,this.queue=[],this.persistQueue(),{sent:0,remaining:0}):r.ok?(this.queue.splice(0,n.length),t=n.length,this.consecutiveFailures=0,this.nextRetryAtMs=0,await this.persistQueue(),{sent:t,remaining:this.queue.length}):(this.scheduleBackoff(),{sent:0,remaining:this.queue.length})}catch{return this.scheduleBackoff(),{sent:0,remaining:this.queue.length}}finally{this.flushing=false;}}async disable(e=true){this.enabled=false,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),e&&(this.queue=[],this.storage?.removeItem?await Promise.resolve(this.storage.removeItem(u)).catch(()=>{}):await this.persistQueue());}async shutdown(){this.isEnabled()&&(this.track({eventType:"sdk.shutdown",status:"ok",component:"NavCore"}),await this.flush()),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.initialized=false;}async register(){if(!this.fetchFn||!this.licenseMeta)return false;try{let e=await this.fetchFn(`${this.endpoint}/v1/telemetry/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({installationId:this.installationId
|
|
1
|
+
var p=new Set(["lat","latitude","lon","lng","longitude","coord","coords","coordinate","coordinates","location","locations","gps","trace","traces","waypoint","waypoints","geometry","route","polyline","origin","destination","address","street","city","postalcode","email","phone","fullname","username","userid","deviceid","advertisingid","idfa","aaid","serial","imei","macaddress","ip","ipaddress","licensekey","token","password","secret"]);function o(i){if(!i)return;let e={};for(let[t,n]of Object.entries(i)){let s=t.toLowerCase().replace(/[^a-z0-9]/g,"");p.has(s)||(typeof n=="string"?e[t.slice(0,64)]=n.slice(0,120):(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t.slice(0,64)]=n));}return Object.keys(e).length>0?e:void 0}var u="navcore_telemetry_queue_v1",d="navcore_telemetry_install_id_v1";function h(){let i=typeof globalThis<"u"?globalThis.crypto:void 0;return i&&typeof i.randomUUID=="function"?i.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return (e==="x"?t:t&3|8).toString(16)})}function f(i){if(typeof Buffer<"u")return Buffer.from(i,"base64").toString("utf8");if(typeof atob=="function")return atob(i);throw new Error("No base64 decoder available")}function c(i){if(!i)return null;try{let[e]=i.split(".");if(!e)return null;let t=JSON.parse(f(e));return typeof t.lid=="string"&&t.lid&&t.pid==="navcore-suite"&&typeof t.bid=="string"&&t.bid?{lid:t.lid,pid:t.pid,bid:t.bid}:null}catch{return null}}function v(){return typeof navigator<"u"&&navigator.product==="ReactNative"?"unknown":typeof process<"u"&&process.versions?.node?"node":typeof window<"u"?"web":"unknown"}var l=class{constructor(e){this.ingestionToken=null;this.tokenExpiresAtMs=0;this.revoked=false;this.queue=[];this.dedupeCache=new Map;this.recentTimestamps=[];this.consecutiveFailures=0;this.nextRetryAtMs=0;this.flushing=false;this.flushTimer=null;this.initialized=false;this.enabled=!!e.enabled,this.endpoint=e.endpoint.replace(/\/+$/,""),this.environment=e.environment??"production",this.platform=e.platform??v(),this.osVersion=e.osVersion,this.sdkVersion=e.sdkVersion??"2.1.0",this.packages=e.packages??{"@ingissa/navcore-core":this.sdkVersion},this.maxQueueSize=Math.max(10,Math.min(e.maxQueueSize??200,1e3)),this.maxBatchSize=Math.max(1,Math.min(e.maxBatchSize??25,100)),this.flushIntervalMs=Math.max(5e3,e.flushIntervalMs??3e4),this.maxEventAgeMs=Math.max(6e4,e.maxEventAgeMs??1440*60*1e3),this.maxRetries=Math.max(1,e.maxRetries??5),this.baseBackoffMs=Math.max(200,e.baseBackoffMs??1e3),this.rateLimitPerMinute=Math.max(5,e.rateLimitPerMinute??60),this.storage=e.storage,this.fetchFn=e.fetchFn??(typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0),this.licenseMeta=e.licenseMetadata??c(e.licenseKey)??{pid:"navcore-core",bid:e.applicationId?.trim()||"navcore-core-app"},this.installationId=e.installationId??h();}isEnabled(){return this.enabled&&!this.revoked}getInstallationId(){return this.installationId}getQueueLength(){return this.queue.length}async start(){!this.isEnabled()||this.initialized||(this.initialized=true,await this.restorePersistedState(),this.track({eventType:"sdk.initialized",status:"ok",component:"NavCore",dedupeKey:`init:${this.installationId}`}),this.flushTimer||(this.flushTimer=setInterval(()=>{this.flush();},this.flushIntervalMs),typeof this.flushTimer.unref=="function"&&this.flushTimer.unref()));}track(e){if(!this.isEnabled())return false;let t=Date.now();if(this.recentTimestamps=this.recentTimestamps.filter(s=>t-s<6e4),this.recentTimestamps.length>=this.rateLimitPerMinute)return false;if(e.dedupeKey){let s=this.dedupeCache.get(e.dedupeKey);if(s&&t-s<1e4)return false;if(this.dedupeCache.set(e.dedupeKey,t),this.dedupeCache.size>500){let r=this.dedupeCache.keys().next().value;r&&this.dedupeCache.delete(r);}}for(this.pruneExpired(t);this.queue.length>=this.maxQueueSize;)this.queue.shift();let n={eventId:h(),eventType:e.eventType,timestamp:new Date(t).toISOString(),sdkVersion:this.sdkVersion,platform:this.platform,status:e.status??"ok",durationMs:typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)?Math.max(0,e.durationMs):void 0,errorCode:e.errorCode?.slice(0,64),component:e.component?.slice(0,64),metadata:o(e.metadata),enqueuedAtMs:t};return this.queue.push(n),this.recentTimestamps.push(t),this.persistQueue(),true}async flush(){if(!this.isEnabled()||this.flushing||this.queue.length===0||!this.fetchFn||!this.licenseMeta)return {sent:0,remaining:this.queue.length};let e=Date.now();if(e<this.nextRetryAtMs)return {sent:0,remaining:this.queue.length};if(this.pruneExpired(e),this.queue.length===0)return {sent:0,remaining:0};this.flushing=true;let t=0;try{if((!this.ingestionToken||e>=this.tokenExpiresAtMs-6e4)&&!await this.register())return this.scheduleBackoff(),{sent:0,remaining:this.queue.length};let n=this.queue.slice(0,this.maxBatchSize),s=n.map(({enqueuedAtMs:a,...m})=>m),r=await this.fetchFn(`${this.endpoint}/v1/telemetry/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ingestionToken}`},body:JSON.stringify({events:s})});return r.status===401?(this.ingestionToken=null,this.scheduleBackoff(),{sent:0,remaining:this.queue.length}):r.status===403?(this.revoked=!0,this.queue=[],this.persistQueue(),{sent:0,remaining:0}):r.ok?(this.queue.splice(0,n.length),t=n.length,this.consecutiveFailures=0,this.nextRetryAtMs=0,await this.persistQueue(),{sent:t,remaining:this.queue.length}):(this.scheduleBackoff(),{sent:0,remaining:this.queue.length})}catch{return this.scheduleBackoff(),{sent:0,remaining:this.queue.length}}finally{this.flushing=false;}}async disable(e=true){this.enabled=false,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),e&&(this.queue=[],this.storage?.removeItem?await Promise.resolve(this.storage.removeItem(u)).catch(()=>{}):await this.persistQueue());}async shutdown(){this.isEnabled()&&(this.track({eventType:"sdk.shutdown",status:"ok",component:"NavCore"}),await this.flush()),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.initialized=false;}async register(){if(!this.fetchFn||!this.licenseMeta)return false;try{let e=await this.fetchFn(`${this.endpoint}/v1/telemetry/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({installationId:this.installationId,...this.licenseMeta.lid?{lid:this.licenseMeta.lid}:{},pid:this.licenseMeta.pid,bid:this.licenseMeta.bid,platform:this.platform,osVersion:this.osVersion,sdkVersion:this.sdkVersion,packages:this.packages,environment:this.environment})});if(e.status===403)return this.revoked=!0,!1;if(!e.ok)return !1;let t=await e.json();return t.ingestionToken?(this.ingestionToken=t.ingestionToken,this.tokenExpiresAtMs=t.expiresAt?Date.parse(t.expiresAt):Date.now()+36e5,!0):!1}catch{return false}}scheduleBackoff(){if(this.consecutiveFailures+=1,this.consecutiveFailures>this.maxRetries){let t=Math.max(1,Math.floor(this.queue.length/2));this.queue.splice(0,t),this.consecutiveFailures=0,this.persistQueue();}let e=Math.min(3e5,this.baseBackoffMs*Math.pow(2,this.consecutiveFailures));this.nextRetryAtMs=Date.now()+e;}pruneExpired(e){let t=e-this.maxEventAgeMs;this.queue.length!==0&&(this.queue=this.queue.filter(n=>n.enqueuedAtMs>=t));}async restorePersistedState(){if(this.storage)try{let e=await this.storage.getItem(d);e&&typeof e=="string"?this.installationId=e:await this.storage.setItem(d,this.installationId);let t=await this.storage.getItem(u);if(t){let n=JSON.parse(t);Array.isArray(n)&&(this.queue=n.slice(-this.maxQueueSize),this.pruneExpired(Date.now()));}}catch{}}async persistQueue(){if(this.storage)try{await this.storage.setItem(u,JSON.stringify(this.queue.slice(-this.maxQueueSize)));}catch{}}};function y(i,e){let t=()=>{e.track({eventType:"route.loaded",status:"ok",component:"NavCore"});},n=()=>{e.track({eventType:"navigation.started",status:"ok",component:"NavCore"});},s=()=>{e.track({eventType:"navigation.off_route",status:"warning",component:"OffRouteFSM"});},r=()=>{e.track({eventType:"navigation.rejoined",status:"ok",component:"OffRouteFSM"});},a=()=>{e.track({eventType:"navigation.completed",status:"ok",component:"NavCore"});};return i.on("routeLoaded",t),i.on("navigationStarted",n),i.on("deviation",s),i.on("rejoined",r),i.on("arrival",a),()=>{i.off("routeLoaded",t),i.off("navigationStarted",n),i.off("deviation",s),i.off("rejoined",r),i.off("arrival",a);}}function g(i,e){let t=[i.subscribe("routeLoaded",()=>{e.track({eventType:"route.loaded",status:"ok",component:"NavigationSession"});}),i.subscribe("navigationStarted",()=>{e.track({eventType:"navigation.started",status:"ok",component:"NavigationSession"});}),i.subscribe("deviation",()=>{e.track({eventType:"navigation.off_route",status:"warning",component:"NavigationSession"});}),i.subscribe("rejoined",()=>{e.track({eventType:"navigation.rejoined",status:"ok",component:"NavigationSession"});}),i.subscribe("arrival",()=>{e.track({eventType:"navigation.completed",status:"ok",component:"NavigationSession"});})];return ()=>{for(let n of t)n();}}export{l as TelemetryClient,y as attachNavCoreTelemetry,g as attachSessionTelemetry,c as extractLicenseMetadata,o as sanitizeTelemetryMetadata};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ingissa/navcore-telemetry",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.1",
|
|
4
4
|
"description": "Optional, non-blocking Deployment Intelligence telemetry client for NavCore SDK",
|
|
5
5
|
"author": "Ingissa <8abnav@gmail.com>",
|
|
6
6
|
"homepage": "https://navcore-web.vercel.app/",
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"build": "tsup",
|
|
37
37
|
"lint": "tsc --noEmit",
|
|
38
38
|
"test": "vitest run",
|
|
39
|
-
"prepublishOnly": "node ../../scripts/build-stamp.mjs --verify && node ../../scripts/check-license.mjs
|
|
39
|
+
"prepublishOnly": "node ../../scripts/build-stamp.mjs --verify && node ../../scripts/check-license.mjs"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"@ingissa/navcore-core": "^2.1.0"
|