@openreplay/tracker 8.0.0-beta.1 → 8.0.1-beta14

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.
Files changed (111) hide show
  1. package/cjs/app/index.d.ts +6 -1
  2. package/cjs/app/index.js +22 -3
  3. package/cjs/app/observer/observer.js +2 -2
  4. package/cjs/app/session.d.ts +10 -0
  5. package/cjs/app/session.js +3 -0
  6. package/cjs/index.d.ts +11 -0
  7. package/cjs/index.js +28 -1
  8. package/cjs/modules/Network/fetchProxy.d.ts +34 -0
  9. package/cjs/modules/Network/fetchProxy.js +240 -0
  10. package/cjs/modules/Network/index.d.ts +3 -0
  11. package/cjs/modules/Network/index.js +9 -0
  12. package/cjs/modules/Network/networkMessage.d.ts +49 -0
  13. package/cjs/modules/Network/networkMessage.js +82 -0
  14. package/cjs/modules/Network/types.d.ts +13 -0
  15. package/cjs/modules/Network/types.js +3 -0
  16. package/cjs/modules/Network/utils.d.ts +11 -0
  17. package/cjs/modules/Network/utils.js +213 -0
  18. package/cjs/modules/Network/xhrProxy.d.ts +47 -0
  19. package/cjs/modules/Network/xhrProxy.js +209 -0
  20. package/cjs/modules/attributeSender.d.ts +14 -0
  21. package/cjs/modules/attributeSender.js +44 -0
  22. package/cjs/modules/console.js +21 -13
  23. package/cjs/modules/featureFlags.d.ts +25 -0
  24. package/cjs/modules/featureFlags.js +100 -0
  25. package/cjs/modules/img.js +4 -4
  26. package/cjs/modules/network.d.ts +3 -4
  27. package/cjs/modules/network.js +13 -3
  28. package/coverage/clover.xml +1412 -900
  29. package/coverage/coverage-final.json +22 -16
  30. package/coverage/lcov-report/index.html +58 -43
  31. package/coverage/lcov-report/main/app/guards.ts.html +42 -42
  32. package/coverage/lcov-report/main/app/index.html +46 -46
  33. package/coverage/lcov-report/main/app/index.ts.html +104 -8
  34. package/coverage/lcov-report/main/app/logger.ts.html +1 -1
  35. package/coverage/lcov-report/main/app/messages.gen.ts.html +146 -146
  36. package/coverage/lcov-report/main/app/observer/iframe_observer.ts.html +1 -1
  37. package/coverage/lcov-report/main/app/observer/iframe_offsets.ts.html +1 -1
  38. package/coverage/lcov-report/main/app/observer/index.html +1 -1
  39. package/coverage/lcov-report/main/app/observer/shadow_root_observer.ts.html +1 -1
  40. package/coverage/lcov-report/main/app/observer/top_observer.ts.html +1 -1
  41. package/coverage/lcov-report/main/app/sanitizer.ts.html +98 -98
  42. package/coverage/lcov-report/main/app/session.ts.html +47 -5
  43. package/coverage/lcov-report/main/app/ticker.ts.html +1 -1
  44. package/coverage/lcov-report/main/index.html +24 -24
  45. package/coverage/lcov-report/main/index.ts.html +138 -6
  46. package/coverage/lcov-report/main/modules/Network/fetchProxy.ts.html +949 -0
  47. package/coverage/lcov-report/main/{vendors/finder → modules/Network}/index.html +72 -12
  48. package/coverage/lcov-report/main/modules/Network/index.ts.html +169 -0
  49. package/coverage/lcov-report/main/{app/nodes.ts.html → modules/Network/networkMessage.ts.html} +130 -115
  50. package/coverage/lcov-report/main/modules/Network/utils.ts.html +700 -0
  51. package/coverage/lcov-report/main/modules/Network/xhrProxy.ts.html +823 -0
  52. package/coverage/lcov-report/main/modules/attributeSender.ts.html +217 -0
  53. package/coverage/lcov-report/main/modules/axiosSpy.ts.html +1 -1
  54. package/coverage/lcov-report/main/modules/connection.ts.html +1 -1
  55. package/coverage/lcov-report/main/modules/console.ts.html +174 -147
  56. package/coverage/lcov-report/main/modules/constructedStyleSheets.ts.html +1 -1
  57. package/coverage/lcov-report/main/modules/cssrules.ts.html +1 -1
  58. package/coverage/lcov-report/main/modules/exception.ts.html +1 -1
  59. package/coverage/lcov-report/main/modules/featureFlags.ts.html +415 -0
  60. package/coverage/lcov-report/main/modules/focus.ts.html +1 -1
  61. package/coverage/lcov-report/main/modules/fonts.ts.html +1 -1
  62. package/coverage/lcov-report/main/modules/img.ts.html +6 -6
  63. package/coverage/lcov-report/main/modules/index.html +54 -24
  64. package/coverage/lcov-report/main/modules/input.ts.html +1 -1
  65. package/coverage/lcov-report/main/modules/mouse.ts.html +1 -1
  66. package/coverage/lcov-report/main/modules/network.ts.html +70 -70
  67. package/coverage/lcov-report/main/modules/performance.ts.html +1 -1
  68. package/coverage/lcov-report/main/modules/scroll.ts.html +1 -1
  69. package/coverage/lcov-report/main/modules/selection.ts.html +1 -1
  70. package/coverage/lcov-report/main/modules/tabs.ts.html +1 -1
  71. package/coverage/lcov-report/main/modules/timing.ts.html +1 -1
  72. package/coverage/lcov-report/main/modules/viewport.ts.html +1 -1
  73. package/coverage/lcov-report/main/utils.ts.html +97 -97
  74. package/coverage/lcov-report/webworker/BatchWriter.ts.html +125 -176
  75. package/coverage/lcov-report/webworker/MessageEncoder.gen.ts.html +88 -88
  76. package/coverage/lcov-report/webworker/PrimitiveEncoder.ts.html +110 -110
  77. package/coverage/lcov-report/webworker/QueueSender.ts.html +140 -110
  78. package/coverage/lcov-report/webworker/index.html +56 -71
  79. package/coverage/lcov-report/webworker/index.ts.html +34 -10
  80. package/coverage/lcov.info +2524 -1552
  81. package/lib/app/index.d.ts +6 -1
  82. package/lib/app/index.js +22 -3
  83. package/lib/app/observer/observer.js +3 -3
  84. package/lib/app/session.d.ts +10 -0
  85. package/lib/app/session.js +3 -0
  86. package/lib/index.d.ts +11 -0
  87. package/lib/index.js +28 -1
  88. package/lib/modules/Network/fetchProxy.d.ts +34 -0
  89. package/lib/modules/Network/fetchProxy.js +234 -0
  90. package/lib/modules/Network/index.d.ts +3 -0
  91. package/lib/modules/Network/index.js +6 -0
  92. package/lib/modules/Network/networkMessage.d.ts +49 -0
  93. package/lib/modules/Network/networkMessage.js +78 -0
  94. package/lib/modules/Network/types.d.ts +13 -0
  95. package/lib/modules/Network/types.js +2 -0
  96. package/lib/modules/Network/utils.d.ts +11 -0
  97. package/lib/modules/Network/utils.js +201 -0
  98. package/lib/modules/Network/xhrProxy.d.ts +47 -0
  99. package/lib/modules/Network/xhrProxy.js +204 -0
  100. package/lib/modules/attributeSender.d.ts +14 -0
  101. package/lib/modules/attributeSender.js +39 -0
  102. package/lib/modules/console.js +21 -13
  103. package/lib/modules/featureFlags.d.ts +25 -0
  104. package/lib/modules/featureFlags.js +97 -0
  105. package/lib/modules/img.js +5 -5
  106. package/lib/modules/network.d.ts +3 -4
  107. package/lib/modules/network.js +13 -3
  108. package/package.json +3 -2
  109. package/coverage/lcov-report/main/app/observer/observer.ts.html +0 -1282
  110. package/coverage/lcov-report/main/vendors/finder/finder.ts.html +0 -1381
  111. package/coverage/lcov-report/webworker/StringDictionary.ts.html +0 -124
@@ -5,6 +5,7 @@ import Sanitizer from './sanitizer.js';
5
5
  import Ticker from './ticker.js';
6
6
  import Logger from './logger.js';
7
7
  import Session from './session.js';
8
+ import AttributeSender from '../modules/attributeSender.js';
8
9
  import type { Options as ObserverOptions } from './observer/top_observer.js';
9
10
  import type { Options as SanitizerOptions } from './sanitizer.js';
10
11
  import type { Options as LoggerOptions } from './logger.js';
@@ -72,15 +73,17 @@ export default class App {
72
73
  private readonly startCallbacks;
73
74
  private readonly stopCallbacks;
74
75
  private readonly commitCallbacks;
75
- private readonly options;
76
+ readonly options: AppOptions;
76
77
  readonly networkOptions?: NetworkOptions;
77
78
  private readonly revID;
78
79
  private activityState;
79
80
  private readonly version;
80
81
  private readonly worker?;
82
+ private featureFlags;
81
83
  private compressionThreshold;
82
84
  private restartAttempts;
83
85
  private readonly bc;
86
+ attributeSender: AttributeSender;
84
87
  constructor(projectKey: string, sessionToken: string | undefined, options: Partial<Options>);
85
88
  private _debug;
86
89
  private _usingOldFetchPlugin;
@@ -118,6 +121,8 @@ export default class App {
118
121
  resolveResourceURL(resourceURL: string): string;
119
122
  isServiceURL(url: string): boolean;
120
123
  active(): boolean;
124
+ isFeatureActive(feature: string): boolean;
125
+ getFeatureFlags(): string[];
121
126
  resetNextPageSession(flag: boolean): void;
122
127
  private _start;
123
128
  /**
package/cjs/app/index.js CHANGED
@@ -11,6 +11,7 @@ const logger_js_1 = require("./logger.js");
11
11
  const session_js_1 = require("./session.js");
12
12
  const fflate_1 = require("fflate");
13
13
  const performance_js_1 = require("../modules/performance.js");
14
+ const attributeSender_js_1 = require("../modules/attributeSender.js");
14
15
  const CANCELED = 'canceled';
15
16
  const START_ERROR = ':(';
16
17
  const UnsuccessfulStart = (reason) => ({ reason, success: false });
@@ -34,7 +35,8 @@ class App {
34
35
  this.stopCallbacks = [];
35
36
  this.commitCallbacks = [];
36
37
  this.activityState = ActivityState.NotActive;
37
- this.version = '8.0.0-beta.1'; // TODO: version compatability check inside each plugin.
38
+ this.version = '8.0.1-beta14'; // TODO: version compatability check inside each plugin.
39
+ this.featureFlags = [];
38
40
  this.compressionThreshold = 24 * 1000;
39
41
  this.restartAttempts = 0;
40
42
  this.bc = new BroadcastChannel('rick');
@@ -70,6 +72,7 @@ class App {
70
72
  this.debug = new logger_js_1.default(this.options.__debug__);
71
73
  this.notify = new logger_js_1.default(this.options.verbose ? logger_js_1.LogLevel.Warnings : logger_js_1.LogLevel.Silent);
72
74
  this.session = new session_js_1.default(this, this.options);
75
+ this.attributeSender = new attributeSender_js_1.default(this);
73
76
  this.session.attachUpdateCallback(({ userID, metadata }) => {
74
77
  if (userID != null) {
75
78
  // TODO: nullable userID
@@ -84,7 +87,7 @@ class App {
84
87
  this.session.applySessionHash(sessionToken);
85
88
  }
86
89
  try {
87
- this.worker = new Worker(URL.createObjectURL(new Blob(['"use strict";class t{constructor(t,i,s,e=10,n=1e3,h){this.onUnauthorised=i,this.onFailure=s,this.MAX_ATTEMPTS_COUNT=e,this.ATTEMPT_TIMEOUT=n,this.onCompress=h,this.attemptsCount=0,this.busy=!1,this.queue=[],this.token=null,this.ingestURL=t+"/v1/web/i",this.isCompressing=void 0!==h}authorise(t){this.token=t,this.busy||this.sendNext()}push(t){this.busy||!this.token?this.queue.push(t):(this.busy=!0,this.isCompressing&&this.onCompress?this.onCompress(t):this.sendBatch(t))}sendNext(){const t=this.queue.shift();t?(this.busy=!0,this.isCompressing&&this.onCompress?this.onCompress(t):this.sendBatch(t)):this.busy=!1}retry(t,i){this.attemptsCount>=this.MAX_ATTEMPTS_COUNT?this.onFailure(`Failed to send batch after ${this.attemptsCount} attempts.`):(this.attemptsCount++,setTimeout(()=>this.sendBatch(t,i),this.ATTEMPT_TIMEOUT*this.attemptsCount))}sendBatch(t,i){this.busy=!0;const s={Authorization:"Bearer "+this.token};i&&(s["Content-Encoding"]="gzip"),null!==this.token?fetch(this.ingestURL,{body:t,method:"POST",headers:s,keepalive:t.length<65536}).then(s=>{if(401===s.status)return this.busy=!1,void this.onUnauthorised();s.status>=400?this.retry(t,i):(this.attemptsCount=0,this.sendNext())}).catch(s=>{console.warn("OpenReplay:",s),this.retry(t,i)}):setTimeout(()=>{this.sendBatch(t,i)},500)}sendCompressed(t){this.sendBatch(t,!0)}sendUncompressed(t){this.sendBatch(t,!1)}clean(){this.sendNext(),setTimeout(()=>{this.token=null,this.queue.length=0},10)}}const i="function"==typeof TextEncoder?new TextEncoder:{encode(t){const i=t.length,s=new Uint8Array(3*i);let e=-1;for(let n=0,h=0,r=0;r!==i;){if(n=t.charCodeAt(r),r+=1,n>=55296&&n<=56319){if(r===i){s[e+=1]=239,s[e+=1]=191,s[e+=1]=189;break}if(h=t.charCodeAt(r),!(h>=56320&&h<=57343)){s[e+=1]=239,s[e+=1]=191,s[e+=1]=189;continue}if(n=1024*(n-55296)+h-56320+65536,r+=1,n>65535){s[e+=1]=240|n>>>18,s[e+=1]=128|n>>>12&63,s[e+=1]=128|n>>>6&63,s[e+=1]=128|63&n;continue}}n<=127?s[e+=1]=0|n:n<=2047?(s[e+=1]=192|n>>>6,s[e+=1]=128|63&n):(s[e+=1]=224|n>>>12,s[e+=1]=128|n>>>6&63,s[e+=1]=128|63&n)}return s.subarray(0,e+1)}};class s extends class{constructor(t){this.size=t,this.offset=0,this.checkpointOffset=0,this.data=new Uint8Array(t)}getCurrentOffset(){return this.offset}checkpoint(){this.checkpointOffset=this.offset}get isEmpty(){return 0===this.offset}skip(t){return this.offset+=t,this.offset<=this.size}set(t,i){this.data.set(t,i)}boolean(t){return this.data[this.offset++]=+t,this.offset<=this.size}uint(t){for((t<0||t>Number.MAX_SAFE_INTEGER)&&(t=0);t>=128;)this.data[this.offset++]=t%256|128,t=Math.floor(t/128);return this.data[this.offset++]=t,this.offset<=this.size}int(t){return t=Math.round(t),this.uint(t>=0?2*t:-2*t-1)}string(t){const s=i.encode(t),e=s.byteLength;return!(!this.uint(e)||this.offset+e>this.size)&&(this.data.set(s,this.offset),this.offset+=e,!0)}reset(){this.offset=0,this.checkpointOffset=0}flush(){const t=this.data.slice(0,this.checkpointOffset);return this.reset(),t}}{encode(t){switch(t[0]){case 0:return this.uint(t[1]);case 4:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3]);case 5:return this.uint(t[1])&&this.uint(t[2]);case 6:return this.int(t[1])&&this.int(t[2]);case 7:return!0;case 8:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.string(t[4])&&this.boolean(t[5]);case 9:case 10:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3]);case 11:return this.uint(t[1]);case 12:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3]);case 13:case 14:return this.uint(t[1])&&this.string(t[2]);case 16:return this.uint(t[1])&&this.int(t[2])&&this.int(t[3]);case 17:return this.uint(t[1])&&this.string(t[2]);case 18:return this.uint(t[1])&&this.string(t[2])&&this.int(t[3]);case 19:return this.uint(t[1])&&this.boolean(t[2]);case 20:return this.uint(t[1])&&this.uint(t[2]);case 21:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.string(t[5])&&this.uint(t[6])&&this.uint(t[7])&&this.uint(t[8]);case 22:return this.string(t[1])&&this.string(t[2]);case 23:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.uint(t[7])&&this.uint(t[8])&&this.uint(t[9]);case 24:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3]);case 27:return this.string(t[1])&&this.string(t[2]);case 28:case 29:return this.string(t[1]);case 30:return this.string(t[1])&&this.string(t[2]);case 37:return this.uint(t[1])&&this.string(t[2])&&this.uint(t[3]);case 38:return this.uint(t[1])&&this.uint(t[2]);case 39:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.uint(t[7]);case 40:return this.string(t[1])&&this.uint(t[2])&&this.string(t[3])&&this.string(t[4]);case 41:return this.string(t[1])&&this.string(t[2]);case 42:return this.string(t[1]);case 44:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3]);case 45:case 46:return this.string(t[1])&&this.string(t[2]);case 47:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3]);case 48:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4]);case 49:return this.int(t[1])&&this.int(t[2])&&this.uint(t[3])&&this.uint(t[4]);case 50:return this.uint(t[1])&&this.string(t[2]);case 51:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3]);case 53:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.string(t[7])&&this.string(t[8]);case 54:return this.uint(t[1])&&this.string(t[2]);case 55:return this.boolean(t[1]);case 57:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4]);case 58:return this.int(t[1]);case 59:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.string(t[5])&&this.string(t[6])&&this.string(t[7]);case 60:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4]);case 61:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3]);case 63:case 64:return this.string(t[1])&&this.string(t[2]);case 67:return this.uint(t[1])&&this.string(t[2])&&this.uint(t[3])&&this.string(t[4]);case 69:return this.uint(t[1])&&this.uint(t[2])&&this.string(t[3])&&this.string(t[4]);case 70:return this.uint(t[1])&&this.uint(t[2]);case 71:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3]);case 73:return this.uint(t[1])&&this.string(t[2])&&this.uint(t[3])&&this.string(t[4]);case 75:case 76:case 77:return this.uint(t[1])&&this.uint(t[2]);case 78:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4]);case 79:return this.string(t[1])&&this.string(t[2]);case 81:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.int(t[4])&&this.string(t[5]);case 82:return this.uint(t[1])&&this.uint(t[2]);case 112:return this.uint(t[1])&&this.string(t[2])&&this.boolean(t[3])&&this.string(t[4])&&this.int(t[5])&&this.int(t[6]);case 113:return this.uint(t[1])&&this.uint(t[2])&&this.string(t[3]);case 114:case 115:return this.uint(t[1]);case 116:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.string(t[7])&&this.string(t[8])&&this.uint(t[9])&&this.boolean(t[10]);case 117:case 118:return this.string(t[1])}}}class e{constructor(){this.idx=1,this.backDict={}}getKey(t){let i=!1;return this.backDict[t]||(i=!0,this.backDict[t]=this.idx++),[this.backDict[t],i]}}class n{constructor(t,i,n,h,r){this.pageNo=t,this.timestamp=i,this.url=n,this.onBatch=h,this.tabId=r,this.nextIndex=0,this.beaconSize=2e5,this.encoder=new s(this.beaconSize),this.strDict=new e,this.sizeBuffer=new Uint8Array(3),this.isEmpty=!0,this.beaconSizeLimit=1e6,this.prepare()}writeType(t){return this.encoder.uint(t[0])}writeFields(t){return this.encoder.encode(t)}writeSizeAt(t,i){for(let i=0;i<3;i++)this.sizeBuffer[i]=t>>8*i;this.encoder.set(this.sizeBuffer,i)}prepare(){if(!this.encoder.isEmpty)return;const t=[81,1,this.pageNo,this.nextIndex,this.timestamp,this.url],i=[118,this.tabId];this.writeType(t),this.writeFields(t),this.writeWithSize(i),this.isEmpty=!0}writeWithSize(t){const i=this.encoder;if(!this.writeType(t)||!i.skip(3))return!1;const s=i.getCurrentOffset(),e=this.writeFields(t);if(e){const e=i.getCurrentOffset()-s;if(e>16777215)return console.warn("OpenReplay: max message size overflow."),!1;this.writeSizeAt(e,s-3),i.checkpoint(),this.isEmpty=this.isEmpty&&0===t[0],this.nextIndex++}return e}setBeaconSizeLimit(t){this.beaconSizeLimit=t}applyDict(t){const[i,s]=this.strDict.getKey(t);return s&&this.writeMessage([50,i,t]),i}writeMessage(t){0===t[0]&&(this.timestamp=t[1]),4===t[0]&&(this.url=t[1]),12===t[0]&&(t=[51,t[1],this.applyDict(t[2]),this.applyDict(t[3])]),this.writeWithSize(t)||(this.finaliseBatch(),this.writeWithSize(t)||(this.encoder=new s(this.beaconSizeLimit),this.prepare(),this.writeWithSize(t)?this.finaliseBatch():console.warn("OpenReplay: beacon size overflow. Skipping large message.",t,this),this.encoder=new s(this.beaconSize),this.prepare()))}finaliseBatch(){if(this.isEmpty)return;const t=this.encoder.flush();this.onBatch(t),this.prepare()}clean(){this.encoder.reset()}}var h;!function(t){t[t.NotActive=0]="NotActive",t[t.Starting=1]="Starting",t[t.Stopping=2]="Stopping",t[t.Active=3]="Active",t[t.Stopped=4]="Stopped"}(h||(h={}));let r=null,u=null,a=h.NotActive;function o(){u&&u.finaliseBatch()}function c(){a=h.Stopping,null!==l&&(clearInterval(l),l=null),u&&(u.clean(),u=null),r&&(r.clean(),setTimeout(()=>{r=null},20)),setTimeout(()=>{a=h.NotActive},100)}function g(){a!==h.Stopped&&(postMessage("restart"),c())}let p,l=null;self.onmessage=({data:i})=>{if(null!=i){if("stop"===i)return o(),c(),a=h.Stopped;if(!Array.isArray(i)){if("compressed"===i.type){if(!r)return console.debug("WebWorker: sender not initialised. Compressed batch."),void g();r.sendCompressed(i.batch)}if("uncompressed"===i.type){if(!r)return console.debug("WebWorker: sender not initialised. Uncompressed batch."),void g();r.sendUncompressed(i.batch)}return"start"===i.type?(a=h.Starting,r=new t(i.ingestPoint,()=>{g()},t=>{!function(t){postMessage({type:"failure",reason:t}),c()}(t)},i.connAttemptCount,i.connAttemptGap,t=>{postMessage({type:"compress",batch:t},[t.buffer])}),u=new n(i.pageNo,i.timestamp,i.url,t=>r&&r.push(t),i.tabId),null===l&&(l=setInterval(o,1e4)),a=h.Active):"auth"===i.type?r?u?(r.authorise(i.token),void(i.beaconSizeLimit&&u.setBeaconSizeLimit(i.beaconSizeLimit))):(console.debug("WebWorker: writer not initialised. Received auth."),void g()):(console.debug("WebWorker: sender not initialised. Received auth."),void g()):void 0}if(null!==u){const t=u;i.forEach(i=>{55===i[0]&&(i[1]?p=setTimeout(()=>g(),18e5):clearTimeout(p)),t.writeMessage(i)})}u||(postMessage("not_init"),g())}else o()};'], { type: 'text/javascript' })));
90
+ this.worker = new Worker(URL.createObjectURL(new Blob(['"use strict";class t{constructor(t,i,s,e=10,n=1e3,r){this.onUnauthorised=i,this.onFailure=s,this.MAX_ATTEMPTS_COUNT=e,this.ATTEMPT_TIMEOUT=n,this.onCompress=r,this.attemptsCount=0,this.busy=!1,this.queue=[],this.token=null,this.ingestURL=t+"/v1/web/i",this.isCompressing=void 0!==r}authorise(t){this.token=t,this.busy||this.sendNext()}push(t){this.busy||!this.token?this.queue.push(t):(this.busy=!0,this.isCompressing&&this.onCompress?this.onCompress(t):this.sendBatch(t))}sendNext(){const t=this.queue.shift();t?(this.busy=!0,this.isCompressing&&this.onCompress?this.onCompress(t):this.sendBatch(t)):this.busy=!1}retry(t,i){this.attemptsCount>=this.MAX_ATTEMPTS_COUNT?this.onFailure(`Failed to send batch after ${this.attemptsCount} attempts.`):(this.attemptsCount++,setTimeout(()=>this.sendBatch(t,i),this.ATTEMPT_TIMEOUT*this.attemptsCount))}sendBatch(t,i){this.busy=!0;const s={Authorization:"Bearer "+this.token};i&&(s["Content-Encoding"]="gzip"),null!==this.token?fetch(this.ingestURL,{body:t,method:"POST",headers:s,keepalive:t.length<65536}).then(s=>{if(401===s.status)return this.busy=!1,void this.onUnauthorised();s.status>=400?this.retry(t,i):(this.attemptsCount=0,this.sendNext())}).catch(s=>{console.warn("OpenReplay:",s),this.retry(t,i)}):setTimeout(()=>{this.sendBatch(t,i)},500)}sendCompressed(t){this.sendBatch(t,!0)}sendUncompressed(t){this.sendBatch(t,!1)}clean(){this.sendNext(),setTimeout(()=>{this.token=null,this.queue.length=0},10)}}const i="function"==typeof TextEncoder?new TextEncoder:{encode(t){const i=t.length,s=new Uint8Array(3*i);let e=-1;for(let n=0,r=0,h=0;h!==i;){if(n=t.charCodeAt(h),h+=1,n>=55296&&n<=56319){if(h===i){s[e+=1]=239,s[e+=1]=191,s[e+=1]=189;break}if(r=t.charCodeAt(h),!(r>=56320&&r<=57343)){s[e+=1]=239,s[e+=1]=191,s[e+=1]=189;continue}if(n=1024*(n-55296)+r-56320+65536,h+=1,n>65535){s[e+=1]=240|n>>>18,s[e+=1]=128|n>>>12&63,s[e+=1]=128|n>>>6&63,s[e+=1]=128|63&n;continue}}n<=127?s[e+=1]=0|n:n<=2047?(s[e+=1]=192|n>>>6,s[e+=1]=128|63&n):(s[e+=1]=224|n>>>12,s[e+=1]=128|n>>>6&63,s[e+=1]=128|63&n)}return s.subarray(0,e+1)}};class s extends class{constructor(t){this.size=t,this.offset=0,this.checkpointOffset=0,this.data=new Uint8Array(t)}getCurrentOffset(){return this.offset}checkpoint(){this.checkpointOffset=this.offset}get isEmpty(){return 0===this.offset}skip(t){return this.offset+=t,this.offset<=this.size}set(t,i){this.data.set(t,i)}boolean(t){return this.data[this.offset++]=+t,this.offset<=this.size}uint(t){for((t<0||t>Number.MAX_SAFE_INTEGER)&&(t=0);t>=128;)this.data[this.offset++]=t%256|128,t=Math.floor(t/128);return this.data[this.offset++]=t,this.offset<=this.size}int(t){return t=Math.round(t),this.uint(t>=0?2*t:-2*t-1)}string(t){const s=i.encode(t),e=s.byteLength;return!(!this.uint(e)||this.offset+e>this.size)&&(this.data.set(s,this.offset),this.offset+=e,!0)}reset(){this.offset=0,this.checkpointOffset=0}flush(){const t=this.data.slice(0,this.checkpointOffset);return this.reset(),t}}{encode(t){switch(t[0]){case 0:return this.uint(t[1]);case 4:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3]);case 5:return this.uint(t[1])&&this.uint(t[2]);case 6:return this.int(t[1])&&this.int(t[2]);case 7:return!0;case 8:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.string(t[4])&&this.boolean(t[5]);case 9:case 10:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3]);case 11:return this.uint(t[1]);case 12:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3]);case 13:case 14:return this.uint(t[1])&&this.string(t[2]);case 16:return this.uint(t[1])&&this.int(t[2])&&this.int(t[3]);case 17:return this.uint(t[1])&&this.string(t[2]);case 18:return this.uint(t[1])&&this.string(t[2])&&this.int(t[3]);case 19:return this.uint(t[1])&&this.boolean(t[2]);case 20:return this.uint(t[1])&&this.uint(t[2]);case 21:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.string(t[5])&&this.uint(t[6])&&this.uint(t[7])&&this.uint(t[8]);case 22:return this.string(t[1])&&this.string(t[2]);case 23:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.uint(t[7])&&this.uint(t[8])&&this.uint(t[9]);case 24:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3]);case 27:return this.string(t[1])&&this.string(t[2]);case 28:case 29:return this.string(t[1]);case 30:return this.string(t[1])&&this.string(t[2]);case 37:return this.uint(t[1])&&this.string(t[2])&&this.uint(t[3]);case 38:return this.uint(t[1])&&this.uint(t[2]);case 39:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.uint(t[7]);case 40:return this.string(t[1])&&this.uint(t[2])&&this.string(t[3])&&this.string(t[4]);case 41:return this.string(t[1])&&this.string(t[2]);case 42:return this.string(t[1]);case 44:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3]);case 45:case 46:return this.string(t[1])&&this.string(t[2]);case 47:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3]);case 48:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4]);case 49:return this.int(t[1])&&this.int(t[2])&&this.uint(t[3])&&this.uint(t[4]);case 50:return this.uint(t[1])&&this.string(t[2]);case 51:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3]);case 53:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.string(t[7])&&this.string(t[8]);case 54:return this.uint(t[1])&&this.string(t[2]);case 55:return this.boolean(t[1]);case 57:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4]);case 58:return this.int(t[1]);case 59:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.string(t[5])&&this.string(t[6])&&this.string(t[7]);case 60:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4]);case 61:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3]);case 63:case 64:return this.string(t[1])&&this.string(t[2]);case 67:return this.uint(t[1])&&this.string(t[2])&&this.uint(t[3])&&this.string(t[4]);case 69:return this.uint(t[1])&&this.uint(t[2])&&this.string(t[3])&&this.string(t[4]);case 70:return this.uint(t[1])&&this.uint(t[2]);case 71:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3]);case 73:return this.uint(t[1])&&this.string(t[2])&&this.uint(t[3])&&this.string(t[4]);case 75:case 76:case 77:return this.uint(t[1])&&this.uint(t[2]);case 78:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4]);case 79:return this.string(t[1])&&this.string(t[2]);case 81:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.int(t[4])&&this.string(t[5]);case 82:return this.uint(t[1])&&this.uint(t[2]);case 112:return this.uint(t[1])&&this.string(t[2])&&this.boolean(t[3])&&this.string(t[4])&&this.int(t[5])&&this.int(t[6]);case 113:return this.uint(t[1])&&this.uint(t[2])&&this.string(t[3]);case 114:case 115:return this.uint(t[1]);case 116:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.string(t[7])&&this.string(t[8])&&this.uint(t[9])&&this.boolean(t[10]);case 117:case 118:return this.string(t[1])}}}class e{constructor(t,i,e,n,r){this.pageNo=t,this.timestamp=i,this.url=e,this.onBatch=n,this.tabId=r,this.nextIndex=0,this.beaconSize=2e5,this.encoder=new s(this.beaconSize),this.sizeBuffer=new Uint8Array(3),this.isEmpty=!0,this.beaconSizeLimit=1e6,this.prepare()}writeType(t){return this.encoder.uint(t[0])}writeFields(t){return this.encoder.encode(t)}writeSizeAt(t,i){for(let i=0;i<3;i++)this.sizeBuffer[i]=t>>8*i;this.encoder.set(this.sizeBuffer,i)}prepare(){if(!this.encoder.isEmpty)return;const t=[81,1,this.pageNo,this.nextIndex,this.timestamp,this.url],i=[118,this.tabId];this.writeType(t),this.writeFields(t),this.writeWithSize(i),this.isEmpty=!0}writeWithSize(t){const i=this.encoder;if(!this.writeType(t)||!i.skip(3))return!1;const s=i.getCurrentOffset(),e=this.writeFields(t);if(e){const e=i.getCurrentOffset()-s;if(e>16777215)return console.warn("OpenReplay: max message size overflow."),!1;this.writeSizeAt(e,s-3),i.checkpoint(),this.isEmpty=this.isEmpty&&0===t[0],this.nextIndex++}return e}setBeaconSizeLimit(t){this.beaconSizeLimit=t}writeMessage(t){0===t[0]&&(this.timestamp=t[1]),4===t[0]&&(this.url=t[1]),this.writeWithSize(t)||(this.finaliseBatch(),this.writeWithSize(t)||(this.encoder=new s(this.beaconSizeLimit),this.prepare(),this.writeWithSize(t)?this.finaliseBatch():console.warn("OpenReplay: beacon size overflow. Skipping large message.",t,this),this.encoder=new s(this.beaconSize),this.prepare()))}finaliseBatch(){if(this.isEmpty)return;const t=this.encoder.flush();this.onBatch(t),this.prepare()}clean(){this.encoder.reset()}}var n;!function(t){t[t.NotActive=0]="NotActive",t[t.Starting=1]="Starting",t[t.Stopping=2]="Stopping",t[t.Active=3]="Active",t[t.Stopped=4]="Stopped"}(n||(n={}));let r=null,h=null,u=n.NotActive;function a(){h&&h.finaliseBatch()}function o(){u=n.Stopping,null!==p&&(clearInterval(p),p=null),h&&(h.clean(),h=null),r&&(r.clean(),setTimeout(()=>{r=null},20)),setTimeout(()=>{u=n.NotActive},100)}function c(){u!==n.Stopped&&(postMessage("restart"),o())}let g,p=null;self.onmessage=({data:i})=>{if(null!=i){if("stop"===i)return a(),o(),u=n.Stopped;if(!Array.isArray(i)){if("compressed"===i.type){if(!r)return console.debug("WebWorker: sender not initialised. Compressed batch."),void c();r.sendCompressed(i.batch)}if("uncompressed"===i.type){if(!r)return console.debug("WebWorker: sender not initialised. Uncompressed batch."),void c();r.sendUncompressed(i.batch)}return"start"===i.type?(u=n.Starting,r=new t(i.ingestPoint,()=>{c()},t=>{!function(t){postMessage({type:"failure",reason:t}),o()}(t)},i.connAttemptCount,i.connAttemptGap,t=>{postMessage({type:"compress",batch:t},[t.buffer])}),h=new e(i.pageNo,i.timestamp,i.url,t=>r&&r.push(t),i.tabId),null===p&&(p=setInterval(a,1e4)),u=n.Active):"auth"===i.type?r?h?(r.authorise(i.token),void(i.beaconSizeLimit&&h.setBeaconSizeLimit(i.beaconSizeLimit))):(console.debug("WebWorker: writer not initialised. Received auth."),void c()):(console.debug("WebWorker: sender not initialised. Received auth."),void c()):void 0}if(null!==h){const t=h;i.forEach(i=>{55===i[0]&&(i[1]?g=setTimeout(()=>c(),18e5):clearTimeout(g)),t.writeMessage(i)})}h||(postMessage("not_init"),c())}else a()};'], { type: 'text/javascript' })));
88
91
  this.worker.onerror = (e) => {
89
92
  this._debug('webworker_error', e);
90
93
  };
@@ -333,6 +336,12 @@ class App {
333
336
  active() {
334
337
  return this.activityState === ActivityState.Active;
335
338
  }
339
+ isFeatureActive(feature) {
340
+ return this.featureFlags.includes(feature);
341
+ }
342
+ getFeatureFlags() {
343
+ return this.featureFlags;
344
+ }
336
345
  resetNextPageSession(flag) {
337
346
  if (flag) {
338
347
  this.sessionStorage.setItem(this.options.session_reset_key, 't');
@@ -411,7 +420,8 @@ class App {
411
420
  delay, // derived from token
412
421
  sessionID, // derived from token
413
422
  startTimestamp, // real startTS (server time), derived from sessionID
414
- } = r;
423
+ userBrowser, userCity, userCountry, userDevice, userOS, userState, } = r;
424
+ // TODO: insert feature flags here
415
425
  if (typeof token !== 'string' ||
416
426
  typeof userUUID !== 'string' ||
417
427
  (typeof startTimestamp !== 'number' && typeof startTimestamp !== 'undefined') ||
@@ -422,6 +432,14 @@ class App {
422
432
  }
423
433
  this.delay = delay;
424
434
  this.session.setSessionToken(token);
435
+ this.session.setUserInfo({
436
+ userBrowser,
437
+ userCity,
438
+ userCountry,
439
+ userDevice,
440
+ userOS,
441
+ userState,
442
+ });
425
443
  this.session.assign({
426
444
  sessionID,
427
445
  timestamp: startTimestamp || timestamp,
@@ -498,6 +516,7 @@ class App {
498
516
  stop(stopWorker = true) {
499
517
  if (this.activityState !== ActivityState.NotActive) {
500
518
  try {
519
+ this.attributeSender.clear();
501
520
  this.sanitizer.clear();
502
521
  this.observer.disconnect();
503
522
  this.nodes.clear();
@@ -115,7 +115,7 @@ class Observer {
115
115
  this.app.send((0, messages_gen_js_1.SetNodeAttributeURLBased)(id, name, value, this.app.getBaseHref()));
116
116
  }
117
117
  else {
118
- this.app.send((0, messages_gen_js_1.SetNodeAttribute)(id, name, value));
118
+ this.app.attributeSender.sendSetAttribute(id, name, value);
119
119
  }
120
120
  return;
121
121
  }
@@ -145,7 +145,7 @@ class Observer {
145
145
  if (name === 'href' || value.length > 1e5) {
146
146
  value = '';
147
147
  }
148
- this.app.send((0, messages_gen_js_1.SetNodeAttribute)(id, name, value));
148
+ this.app.attributeSender.sendSetAttribute(id, name, value);
149
149
  }
150
150
  sendNodeData(id, parentElement, data) {
151
151
  if ((0, guards_js_1.hasTag)(parentElement, 'style')) {
@@ -1,4 +1,12 @@
1
1
  import type App from './index.js';
2
+ interface UserInfo {
3
+ userBrowser: string;
4
+ userCity: string;
5
+ userCountry: string;
6
+ userDevice: string;
7
+ userOS: string;
8
+ userState: string;
9
+ }
2
10
  interface SessionInfo {
3
11
  sessionID: string | undefined;
4
12
  metadata: Record<string, string>;
@@ -22,12 +30,14 @@ export default class Session {
22
30
  private timestamp;
23
31
  private projectID;
24
32
  private tabId;
33
+ userInfo: UserInfo;
25
34
  constructor(app: App, options: Options);
26
35
  attachUpdateCallback(cb: OnUpdateCallback): void;
27
36
  private handleUpdate;
28
37
  assign(newInfo: Partial<SessionInfo>): void;
29
38
  setMetadata(key: string, value: string): void;
30
39
  setUserID(userID: string): void;
40
+ setUserInfo(userInfo: UserInfo): void;
31
41
  private getPageNumber;
32
42
  incPageNo(): number;
33
43
  getSessionToken(): string | undefined;
@@ -50,6 +50,9 @@ class Session {
50
50
  this.userID = userID;
51
51
  this.handleUpdate({ userID });
52
52
  }
53
+ setUserInfo(userInfo) {
54
+ this.userInfo = userInfo;
55
+ }
53
56
  getPageNumber() {
54
57
  const pageNoStr = this.app.sessionStorage.getItem(this.options.session_pageno_key);
55
58
  if (pageNoStr == null) {
package/cjs/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export { default as App } from './app/index.js';
3
3
  import * as _Messages from './app/messages.gen.js';
4
4
  export declare const Messages: typeof _Messages;
5
5
  export { SanitizeLevel } from './app/sanitizer.js';
6
+ import FeatureFlags, { IFeatureFlag } from './modules/featureFlags.js';
6
7
  import type { Options as AppOptions } from './app/index.js';
7
8
  import type { Options as ConsoleOptions } from './modules/console.js';
8
9
  import type { Options as ExceptionOptions } from './modules/exception.js';
@@ -21,12 +22,22 @@ export type Options = Partial<AppOptions & ConsoleOptions & ExceptionOptions & I
21
22
  autoResetOnWindowOpen?: boolean;
22
23
  network?: NetworkOptions;
23
24
  mouse?: MouseHandlerOptions;
25
+ flags?: {
26
+ onFlagsLoad?: (flags: IFeatureFlag[]) => void;
27
+ };
24
28
  __DISABLE_SECURE_MODE?: boolean;
25
29
  };
26
30
  export default class API {
27
31
  private readonly options;
32
+ featureFlags: FeatureFlags;
28
33
  private readonly app;
29
34
  constructor(options: Options);
35
+ isFlagEnabled(flagName: string): boolean;
36
+ onFlagsLoad(callback: (flags: IFeatureFlag[]) => void): void;
37
+ clearPersistFlags(): void;
38
+ reloadFlags(): Promise<void>;
39
+ getFeatureFlag(flagName: string): IFeatureFlag | undefined;
40
+ getAllFeatureFlags(): IFeatureFlag[];
30
41
  use<T>(fn: (app: App | null, options?: Options) => T): T;
31
42
  isActive(): boolean;
32
43
  start(startOpts?: Partial<StartOptions>): Promise<StartPromiseReturn>;
package/cjs/index.js CHANGED
@@ -27,6 +27,7 @@ const constructedStyleSheets_js_1 = require("./modules/constructedStyleSheets.js
27
27
  const selection_js_1 = require("./modules/selection.js");
28
28
  const tabs_js_1 = require("./modules/tabs.js");
29
29
  const utils_js_1 = require("./utils.js");
30
+ const featureFlags_js_1 = require("./modules/featureFlags.js");
30
31
  const DOCS_SETUP = '/installation/javascript-sdk';
31
32
  function processOptions(obj) {
32
33
  if (obj == null) {
@@ -120,7 +121,15 @@ class API {
120
121
  (0, network_js_1.default)(app, options.network);
121
122
  (0, selection_js_1.default)(app);
122
123
  (0, tabs_js_1.default)(app);
124
+ this.featureFlags = new featureFlags_js_1.default(app);
123
125
  window.__OPENREPLAY__ = this;
126
+ app.attachStartCallback(() => {
127
+ var _a;
128
+ if ((_a = options.flags) === null || _a === void 0 ? void 0 : _a.onFlagsLoad) {
129
+ this.onFlagsLoad(options.flags.onFlagsLoad);
130
+ }
131
+ void this.featureFlags.reloadFlags();
132
+ });
124
133
  if (options.autoResetOnWindowOpen) {
125
134
  const wOpen = window.open;
126
135
  app.attachStartCallback(() => {
@@ -144,13 +153,31 @@ class API {
144
153
  // no-cors issue only with text/plain or not-set Content-Type
145
154
  // req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
146
155
  req.send(JSON.stringify({
147
- trackerVersion: '8.0.0-beta.1',
156
+ trackerVersion: '8.0.1-beta14',
148
157
  projectKey: options.projectKey,
149
158
  doNotTrack,
150
159
  // TODO: add precise reason (an exact API missing)
151
160
  }));
152
161
  }
153
162
  }
163
+ isFlagEnabled(flagName) {
164
+ return this.featureFlags.isFlagEnabled(flagName);
165
+ }
166
+ onFlagsLoad(callback) {
167
+ this.featureFlags.onFlagsLoad(callback);
168
+ }
169
+ clearPersistFlags() {
170
+ this.featureFlags.clearPersistFlags();
171
+ }
172
+ reloadFlags() {
173
+ return this.featureFlags.reloadFlags();
174
+ }
175
+ getFeatureFlag(flagName) {
176
+ return this.featureFlags.getFeatureFlag(flagName);
177
+ }
178
+ getAllFeatureFlags() {
179
+ return this.featureFlags.flags;
180
+ }
154
181
  use(fn) {
155
182
  return fn(this.app, this.options);
156
183
  }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * I took inspiration in few stack exchange posts
3
+ * and Tencent vConsole library (MIT)
4
+ * by wrapping the XMLHttpRequest object in a Proxy
5
+ * we can intercept the network requests
6
+ * in not-so-hacky way
7
+ * */
8
+ import NetworkMessage from './networkMessage.js';
9
+ import { RequestResponseData } from './types.js';
10
+ import { NetworkRequest } from '../../common/messages.gen.js';
11
+ export declare class ResponseProxyHandler<T extends Response> implements ProxyHandler<T> {
12
+ resp: Response;
13
+ item: NetworkMessage;
14
+ constructor(resp: T, item: NetworkMessage);
15
+ set(target: T, key: string, value: (args: any[]) => any): boolean;
16
+ get(target: T, key: string): any;
17
+ protected mockReader(): void;
18
+ }
19
+ export declare class FetchProxyHandler<T extends typeof fetch> implements ProxyHandler<T> {
20
+ private readonly ignoredHeaders;
21
+ private readonly setSessionTokenHeader;
22
+ private readonly sanitize;
23
+ private readonly sendMessage;
24
+ private readonly isServiceUrl;
25
+ constructor(ignoredHeaders: boolean | string[], setSessionTokenHeader: (cb: (name: string, value: string) => void) => void, sanitize: (data: RequestResponseData) => RequestResponseData, sendMessage: (item: NetworkRequest) => void, isServiceUrl: (url: string) => boolean);
26
+ apply(target: T, thisArg: typeof window, argsList: [RequestInfo | URL, RequestInit]): any;
27
+ protected beforeFetch(item: NetworkMessage, input: RequestInfo, init?: RequestInit): void;
28
+ protected afterFetch(item: NetworkMessage): (resp: Response) => Response;
29
+ protected handleResponseBody(resp: Response, item: NetworkMessage): Promise<ArrayBuffer> | Promise<string>;
30
+ }
31
+ export default class FetchProxy {
32
+ static origFetch: typeof fetch;
33
+ static create(ignoredHeaders: boolean | string[], setSessionTokenHeader: (cb: (name: string, value: string) => void) => void, sanitize: (data: RequestResponseData) => RequestResponseData, sendMessage: (item: NetworkRequest) => void, isServiceUrl: (url: string) => boolean): typeof fetch;
34
+ }
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FetchProxyHandler = exports.ResponseProxyHandler = void 0;
4
+ /**
5
+ * I took inspiration in few stack exchange posts
6
+ * and Tencent vConsole library (MIT)
7
+ * by wrapping the XMLHttpRequest object in a Proxy
8
+ * we can intercept the network requests
9
+ * in not-so-hacky way
10
+ * */
11
+ const networkMessage_js_1 = require("./networkMessage.js");
12
+ const utils_js_1 = require("./utils.js");
13
+ class ResponseProxyHandler {
14
+ constructor(resp, item) {
15
+ this.resp = resp;
16
+ this.item = item;
17
+ this.mockReader();
18
+ }
19
+ set(target, key, value) {
20
+ return Reflect.set(target, key, value);
21
+ }
22
+ get(target, key) {
23
+ const value = Reflect.get(target, key);
24
+ switch (key) {
25
+ case 'arrayBuffer':
26
+ case 'blob':
27
+ case 'formData':
28
+ case 'json':
29
+ case 'text':
30
+ return () => {
31
+ this.item.responseType = key.toLowerCase();
32
+ // @ts-ignore
33
+ return value.apply(target).then((resp) => {
34
+ this.item.response = (0, utils_js_1.getStringResponseByType)(this.item.responseType, resp);
35
+ return resp;
36
+ });
37
+ };
38
+ }
39
+ if (typeof value === 'function') {
40
+ return value.bind(target);
41
+ }
42
+ else {
43
+ return value;
44
+ }
45
+ }
46
+ mockReader() {
47
+ let readerReceivedValue;
48
+ if (!this.resp.body) {
49
+ // some browsers do not return `body` in some cases, like `OPTIONS` method
50
+ return;
51
+ }
52
+ if (typeof this.resp.body.getReader !== 'function') {
53
+ return;
54
+ }
55
+ const _getReader = this.resp.body.getReader;
56
+ // @ts-ignore
57
+ this.resp.body.getReader = () => {
58
+ const reader = _getReader.apply(this.resp.body);
59
+ // when readyState is already 4,
60
+ // it's not a chunked stream, or it had already been read.
61
+ // so should not update status.
62
+ if (this.item.readyState === networkMessage_js_1.RequestState.DONE) {
63
+ return reader;
64
+ }
65
+ const _read = reader.read;
66
+ const _cancel = reader.cancel;
67
+ this.item.responseType = 'arraybuffer';
68
+ // @ts-ignore
69
+ reader.read = () => {
70
+ return _read.apply(reader).then((result) => {
71
+ if (!readerReceivedValue) {
72
+ // @ts-ignore
73
+ readerReceivedValue = new Uint8Array(result.value);
74
+ }
75
+ else {
76
+ const newValue = new Uint8Array(readerReceivedValue.length + result.value.length);
77
+ newValue.set(readerReceivedValue);
78
+ newValue.set(result.value, readerReceivedValue.length);
79
+ readerReceivedValue = newValue;
80
+ }
81
+ this.item.endTime = performance.now();
82
+ this.item.duration = this.item.endTime - (this.item.startTime || this.item.endTime);
83
+ this.item.readyState = result.done ? 4 : 3;
84
+ this.item.statusText = result.done ? String(this.item.status) : 'Loading';
85
+ this.item.responseSize = readerReceivedValue.length;
86
+ this.item.responseSizeText = (0, utils_js_1.formatByteSize)(this.item.responseSize);
87
+ if (result.done) {
88
+ this.item.response = (0, utils_js_1.getStringResponseByType)(this.item.responseType, readerReceivedValue);
89
+ }
90
+ return result;
91
+ });
92
+ };
93
+ reader.cancel = (...args) => {
94
+ this.item.cancelState = 2;
95
+ this.item.statusText = 'Cancel';
96
+ this.item.endTime = performance.now();
97
+ this.item.duration = this.item.endTime - (this.item.startTime || this.item.endTime);
98
+ this.item.response = (0, utils_js_1.getStringResponseByType)(this.item.responseType, readerReceivedValue);
99
+ return _cancel.apply(reader, args);
100
+ };
101
+ return reader;
102
+ };
103
+ }
104
+ }
105
+ exports.ResponseProxyHandler = ResponseProxyHandler;
106
+ class FetchProxyHandler {
107
+ constructor(ignoredHeaders, setSessionTokenHeader, sanitize, sendMessage, isServiceUrl) {
108
+ this.ignoredHeaders = ignoredHeaders;
109
+ this.setSessionTokenHeader = setSessionTokenHeader;
110
+ this.sanitize = sanitize;
111
+ this.sendMessage = sendMessage;
112
+ this.isServiceUrl = isServiceUrl;
113
+ }
114
+ apply(target, thisArg, argsList) {
115
+ const input = argsList[0];
116
+ const init = argsList[1];
117
+ const isORUrl = input instanceof URL || typeof input === 'string'
118
+ ? this.isServiceUrl(String(input))
119
+ : this.isServiceUrl(String(input.url));
120
+ if (isORUrl) {
121
+ return target.apply(window, argsList);
122
+ }
123
+ const item = new networkMessage_js_1.default(this.ignoredHeaders, this.setSessionTokenHeader, this.sanitize);
124
+ this.beforeFetch(item, input, init);
125
+ return target.apply(window, argsList)
126
+ .then(this.afterFetch(item))
127
+ .catch((e) => {
128
+ // mock finally
129
+ item.endTime = performance.now();
130
+ item.duration = item.endTime - (item.startTime || item.endTime);
131
+ throw e;
132
+ });
133
+ }
134
+ beforeFetch(item, input, init) {
135
+ let url, method = 'GET', requestHeader = {};
136
+ // handle `input` content
137
+ if (typeof input === 'string') {
138
+ // when `input` is a string
139
+ method = (init === null || init === void 0 ? void 0 : init.method) || 'GET';
140
+ url = (0, utils_js_1.getURL)(input);
141
+ requestHeader = (init === null || init === void 0 ? void 0 : init.headers) || {};
142
+ }
143
+ else {
144
+ // when `input` is a `Request` object
145
+ method = input.method || 'GET';
146
+ url = (0, utils_js_1.getURL)(input.url);
147
+ requestHeader = input.headers;
148
+ }
149
+ item.method = method;
150
+ item.requestType = 'fetch';
151
+ item.requestHeader = requestHeader;
152
+ item.url = url.toString();
153
+ item.name = (url.pathname.split('/').pop() || '') + url.search;
154
+ item.status = 0;
155
+ item.statusText = 'Pending';
156
+ item.readyState = 1;
157
+ if (!item.startTime) {
158
+ // UNSENT
159
+ item.startTime = performance.now();
160
+ }
161
+ if (Object.prototype.toString.call(requestHeader) === '[object Headers]') {
162
+ item.requestHeader = {};
163
+ for (const [key, value] of requestHeader) {
164
+ item.requestHeader[key] = value;
165
+ }
166
+ }
167
+ else {
168
+ item.requestHeader = requestHeader;
169
+ }
170
+ // save GET data
171
+ if (url.search && url.searchParams) {
172
+ item.getData = {};
173
+ for (const [key, value] of url.searchParams) {
174
+ item.getData[key] = value;
175
+ }
176
+ }
177
+ // save POST data
178
+ if (init === null || init === void 0 ? void 0 : init.body) {
179
+ item.requestData = (0, utils_js_1.genStringBody)(init.body);
180
+ }
181
+ }
182
+ afterFetch(item) {
183
+ return (resp) => {
184
+ item.endTime = performance.now();
185
+ item.duration = item.endTime - (item.startTime || item.endTime);
186
+ item.status = resp.status;
187
+ item.statusText = String(resp.status);
188
+ let isChunked = false;
189
+ item.header = {};
190
+ for (const [key, value] of resp.headers) {
191
+ item.header[key] = value;
192
+ isChunked = value.toLowerCase().indexOf('chunked') > -1 ? true : isChunked;
193
+ }
194
+ if (isChunked) {
195
+ // when `transfer-encoding` is chunked, the response is a stream which is under loading,
196
+ // so the `readyState` should be 3 (Loading),
197
+ // and the response should NOT be `clone()` which will affect stream reading.
198
+ item.readyState = 3;
199
+ }
200
+ else {
201
+ // Otherwise, not chunked, the response is not a stream,
202
+ // so it's completed and can be cloned for `text()` calling.
203
+ item.readyState = 4;
204
+ void this.handleResponseBody(resp.clone(), item).then((responseValue) => {
205
+ item.responseSize =
206
+ typeof responseValue === 'string' ? responseValue.length : responseValue.byteLength;
207
+ item.responseSizeText = (0, utils_js_1.formatByteSize)(item.responseSize);
208
+ item.response = (0, utils_js_1.getStringResponseByType)(item.responseType, responseValue);
209
+ this.sendMessage(item.getMessage());
210
+ });
211
+ }
212
+ return new Proxy(resp, new ResponseProxyHandler(resp, item));
213
+ };
214
+ }
215
+ handleResponseBody(resp, item) {
216
+ // parse response body by Content-Type
217
+ const contentType = resp.headers.get('content-type');
218
+ if (contentType && contentType.includes('application/json')) {
219
+ item.responseType = 'json';
220
+ return resp.text();
221
+ }
222
+ else if (contentType &&
223
+ (contentType.includes('text/html') || contentType.includes('text/plain'))) {
224
+ item.responseType = 'text';
225
+ return resp.text();
226
+ }
227
+ else {
228
+ item.responseType = 'arraybuffer';
229
+ return resp.arrayBuffer();
230
+ }
231
+ }
232
+ }
233
+ exports.FetchProxyHandler = FetchProxyHandler;
234
+ class FetchProxy {
235
+ static create(ignoredHeaders, setSessionTokenHeader, sanitize, sendMessage, isServiceUrl) {
236
+ return new Proxy(fetch, new FetchProxyHandler(ignoredHeaders, setSessionTokenHeader, sanitize, sendMessage, isServiceUrl));
237
+ }
238
+ }
239
+ exports.default = FetchProxy;
240
+ FetchProxy.origFetch = fetch;
@@ -0,0 +1,3 @@
1
+ import { RequestResponseData } from './types.js';
2
+ import { NetworkRequest } from '../../common/messages.gen.js';
3
+ export default function setProxy(context: typeof globalThis, ignoredHeaders: boolean | string[], setSessionTokenHeader: (cb: (name: string, value: string) => void) => void, sanitize: (data: RequestResponseData) => RequestResponseData, sendMessage: (message: NetworkRequest) => void, isServiceUrl: (url: string) => boolean): void;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const fetchProxy_js_1 = require("./fetchProxy.js");
4
+ const xhrProxy_js_1 = require("./xhrProxy.js");
5
+ function setProxy(context, ignoredHeaders, setSessionTokenHeader, sanitize, sendMessage, isServiceUrl) {
6
+ context.XMLHttpRequest = xhrProxy_js_1.default.create(ignoredHeaders, setSessionTokenHeader, sanitize, sendMessage, isServiceUrl);
7
+ context.fetch = fetchProxy_js_1.default.create(ignoredHeaders, setSessionTokenHeader, sanitize, sendMessage, isServiceUrl);
8
+ }
9
+ exports.default = setProxy;
@@ -0,0 +1,49 @@
1
+ import { RequestResponseData } from './types.js';
2
+ export type httpMethod = '' | 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH';
3
+ export declare enum RequestState {
4
+ UNSENT = 0,
5
+ OPENED = 1,
6
+ HEADERS_RECEIVED = 2,
7
+ LOADING = 3,
8
+ DONE = 4
9
+ }
10
+ /**
11
+ * I know we're not using most of the information from this class
12
+ * but it can be useful in the future if we will decide to display more stuff in our ui
13
+ * */
14
+ export default class NetworkMessage {
15
+ private readonly ignoredHeaders;
16
+ private readonly setSessionTokenHeader;
17
+ private readonly sanitize;
18
+ id: string;
19
+ name?: string;
20
+ method: httpMethod;
21
+ url: string;
22
+ status: number;
23
+ statusText?: string;
24
+ cancelState?: 0 | 1 | 2 | 3;
25
+ readyState?: RequestState;
26
+ header: {
27
+ [key: string]: string;
28
+ };
29
+ responseType: XMLHttpRequest['responseType'];
30
+ requestType: 'xhr' | 'fetch' | 'ping' | 'custom';
31
+ requestHeader: HeadersInit;
32
+ response: any;
33
+ responseSize: number;
34
+ responseSizeText: string;
35
+ startTime: number;
36
+ endTime: number;
37
+ duration: number;
38
+ getData: {
39
+ [key: string]: string;
40
+ };
41
+ requestData: string | null;
42
+ constructor(ignoredHeaders: boolean | string[], setSessionTokenHeader: (cb: (name: string, value: string) => void) => void, sanitize: (data: RequestResponseData) => RequestResponseData);
43
+ getMessage(): import("../../common/messages.gen.js").NetworkRequest;
44
+ writeHeaders(): {
45
+ reqHs: Record<string, string>;
46
+ resHs: Record<string, string>;
47
+ };
48
+ isHeaderIgnored(key: string): boolean;
49
+ }