@cloudcare/browser-core 3.2.28 → 3.2.29

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 (47) hide show
  1. package/cjs/dataMap.js +1 -0
  2. package/cjs/dataMap.js.map +1 -1
  3. package/cjs/index.js +7 -0
  4. package/cjs/index.js.map +1 -1
  5. package/cjs/session/sessionConstants.js +5 -1
  6. package/cjs/session/sessionConstants.js.map +1 -1
  7. package/cjs/session/sessionInCookie.js +1 -1
  8. package/cjs/session/sessionInCookie.js.map +1 -1
  9. package/cjs/session/sessionInLocalStorage.js +1 -1
  10. package/cjs/session/sessionInLocalStorage.js.map +1 -1
  11. package/cjs/session/sessionStore.js +18 -5
  12. package/cjs/session/sessionStore.js.map +1 -1
  13. package/cjs/session/sessionStoreOperations.js +34 -8
  14. package/cjs/session/sessionStoreOperations.js.map +1 -1
  15. package/cjs/transport/batch.js +3 -1
  16. package/cjs/transport/batch.js.map +1 -1
  17. package/cjs/transport/httpRequest.js +40 -6
  18. package/cjs/transport/httpRequest.js.map +1 -1
  19. package/esm/dataMap.js +1 -0
  20. package/esm/dataMap.js.map +1 -1
  21. package/esm/index.js +1 -1
  22. package/esm/index.js.map +1 -1
  23. package/esm/session/sessionConstants.js +4 -0
  24. package/esm/session/sessionConstants.js.map +1 -1
  25. package/esm/session/sessionInCookie.js +2 -2
  26. package/esm/session/sessionInCookie.js.map +1 -1
  27. package/esm/session/sessionInLocalStorage.js +2 -2
  28. package/esm/session/sessionInLocalStorage.js.map +1 -1
  29. package/esm/session/sessionStore.js +18 -5
  30. package/esm/session/sessionStore.js.map +1 -1
  31. package/esm/session/sessionStoreOperations.js +34 -9
  32. package/esm/session/sessionStoreOperations.js.map +1 -1
  33. package/esm/transport/batch.js +3 -1
  34. package/esm/transport/batch.js.map +1 -1
  35. package/esm/transport/httpRequest.js +40 -6
  36. package/esm/transport/httpRequest.js.map +1 -1
  37. package/package.json +2 -2
  38. package/src/dataMap.js +1 -0
  39. package/src/index.js +2 -1
  40. package/src/session/sessionConstants.js +4 -0
  41. package/src/session/sessionInCookie.js +3 -2
  42. package/src/session/sessionInLocalStorage.js +4 -2
  43. package/src/session/sessionStore.js +27 -8
  44. package/src/session/sessionStoreOperations.js +31 -13
  45. package/src/transport/batch.js +3 -1
  46. package/src/transport/httpRequest.js +53 -14
  47. package/types/index.d.ts +16 -2
@@ -1,8 +1,23 @@
1
+ var _excluded = ["lock"];
2
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
3
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
4
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
5
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
6
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
7
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
8
+ function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
9
+ function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
1
10
  import { setTimeout } from '../helper/timer';
2
- import { UUID, assign } from '../helper/tools';
3
- import { expandSessionState, isSessionInExpiredState, isSessionInNotStartedState } from './sessionState';
11
+ import { UUID, assign, ONE_SECOND, timeStampNow, elapsed } from '../helper/tools';
12
+ import { expandSessionState, isSessionInExpiredState } from './sessionState';
13
+ import { addTelemetryDebug } from '../telemetry/telemetry';
4
14
  export var LOCK_RETRY_DELAY = 10;
5
15
  export var LOCK_MAX_TRIES = 100;
16
+
17
+ // Locks should be hold for a few milliseconds top, just the time it takes to read and write a
18
+ // cookie. Using one second should be enough in most situations.
19
+ export var LOCK_EXPIRATION_DELAY = ONE_SECOND;
20
+ var LOCK_SEPARATOR = '--';
6
21
  var bufferedOperations = [];
7
22
  var ongoingOperations;
8
23
  export function processSessionStoreOperations(operations, sessionStoreStrategy) {
@@ -16,14 +31,12 @@ export function processSessionStoreOperations(operations, sessionStoreStrategy)
16
31
  }));
17
32
  };
18
33
  var retrieveStore = function retrieveStore() {
19
- var session = sessionStoreStrategy.retrieveSession();
20
- var lock = session.lock;
21
- if (session.lock) {
22
- delete session.lock;
23
- }
34
+ var _sessionStoreStrategy = sessionStoreStrategy.retrieveSession(),
35
+ lock = _sessionStoreStrategy.lock,
36
+ session = _objectWithoutProperties(_sessionStoreStrategy, _excluded);
24
37
  return {
25
38
  session: session,
26
- lock: lock
39
+ lock: lock && !isLockExpired(lock) ? lock : undefined
27
40
  };
28
41
  };
29
42
  if (!ongoingOperations) {
@@ -34,6 +47,9 @@ export function processSessionStoreOperations(operations, sessionStoreStrategy)
34
47
  return;
35
48
  }
36
49
  if (isLockEnabled && numberOfRetries >= LOCK_MAX_TRIES) {
50
+ addTelemetryDebug('Aborted session operation after max lock retries', {
51
+ currentStore: retrieveStore()
52
+ });
37
53
  next(sessionStoreStrategy);
38
54
  return;
39
55
  }
@@ -46,7 +62,7 @@ export function processSessionStoreOperations(operations, sessionStoreStrategy)
46
62
  return;
47
63
  }
48
64
  // acquire lock
49
- currentLock = UUID();
65
+ currentLock = createLock();
50
66
  persistWithLock(currentStore.session);
51
67
  // if lock is not acquired, retry later
52
68
  currentStore = retrieveStore();
@@ -105,4 +121,13 @@ function next(sessionStore) {
105
121
  processSessionStoreOperations(nextOperations, sessionStore);
106
122
  }
107
123
  }
124
+ export function createLock() {
125
+ return UUID() + LOCK_SEPARATOR + timeStampNow();
126
+ }
127
+ function isLockExpired(lock) {
128
+ var _lock$split = lock.split(LOCK_SEPARATOR),
129
+ _lock$split2 = _slicedToArray(_lock$split, 2),
130
+ timeStamp = _lock$split2[1];
131
+ return !timeStamp || elapsed(Number(timeStamp), timeStampNow()) > LOCK_EXPIRATION_DELAY;
132
+ }
108
133
  //# sourceMappingURL=sessionStoreOperations.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sessionStoreOperations.js","names":["setTimeout","UUID","assign","expandSessionState","isSessionInExpiredState","isSessionInNotStartedState","LOCK_RETRY_DELAY","LOCK_MAX_TRIES","bufferedOperations","ongoingOperations","processSessionStoreOperations","operations","sessionStoreStrategy","numberOfRetries","arguments","length","undefined","isLockEnabled","persistSession","expireSession","persistWithLock","session","lock","currentLock","retrieveStore","retrieveSession","push","next","currentStore","retryLater","processedSession","process","after","sessionStore","currentNumberOfRetries","nextOperations","shift"],"sources":["../../src/session/sessionStoreOperations.js"],"sourcesContent":["import { setTimeout } from '../helper/timer'\nimport { UUID, assign } from '../helper/tools'\nimport {\n expandSessionState,\n isSessionInExpiredState,\n isSessionInNotStartedState\n} from './sessionState'\n\nexport const LOCK_RETRY_DELAY = 10\nexport const LOCK_MAX_TRIES = 100\nconst bufferedOperations = []\nlet ongoingOperations\n\nexport function processSessionStoreOperations(\n operations,\n sessionStoreStrategy,\n numberOfRetries = 0\n) {\n const { isLockEnabled, persistSession, expireSession } = sessionStoreStrategy\n const persistWithLock = function (session) {\n return persistSession(assign({}, session, { lock: currentLock }))\n }\n const retrieveStore = function () {\n const session = sessionStoreStrategy.retrieveSession()\n const lock = session.lock\n if (session.lock) {\n delete session.lock\n }\n\n return {\n session,\n lock\n }\n }\n\n if (!ongoingOperations) {\n ongoingOperations = operations\n }\n if (operations !== ongoingOperations) {\n bufferedOperations.push(operations)\n return\n }\n if (isLockEnabled && numberOfRetries >= LOCK_MAX_TRIES) {\n next(sessionStoreStrategy)\n return\n }\n let currentLock\n let currentStore = retrieveStore()\n if (isLockEnabled) {\n // if someone has lock, retry later\n if (currentStore.lock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n // acquire lock\n currentLock = UUID()\n persistWithLock(currentStore.session)\n // if lock is not acquired, retry later\n currentStore = retrieveStore()\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n }\n let processedSession = operations.process(currentStore.session)\n if (isLockEnabled) {\n // if lock corrupted after process, retry later\n currentStore = retrieveStore()\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n }\n if (processedSession) {\n if (isSessionInExpiredState(processedSession)) {\n expireSession()\n } else {\n expandSessionState(processedSession)\n isLockEnabled\n ? persistWithLock(processedSession)\n : persistSession(processedSession)\n }\n }\n if (isLockEnabled) {\n // correctly handle lock around expiration would require to handle this case properly at several levels\n // since we don't have evidence of lock issues around expiration, let's just not do the corruption check for it\n if (!(processedSession && isSessionInExpiredState(processedSession))) {\n // if lock corrupted after persist, retry later\n currentStore = retrieveStore()\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n persistSession(currentStore.session)\n processedSession = currentStore.session\n }\n }\n // call after even if session is not persisted in order to perform operations on\n // up-to-date session state value => the value could have been modified by another tab\n if (operations.after) {\n operations.after(processedSession || currentStore.session)\n }\n next(sessionStoreStrategy)\n}\n\nfunction retryLater(operations, sessionStore, currentNumberOfRetries) {\n setTimeout(function () {\n processSessionStoreOperations(\n operations,\n sessionStore,\n currentNumberOfRetries + 1\n )\n }, LOCK_RETRY_DELAY)\n}\n\nfunction next(sessionStore) {\n ongoingOperations = undefined\n const nextOperations = bufferedOperations.shift()\n if (nextOperations) {\n processSessionStoreOperations(nextOperations, sessionStore)\n }\n}\n"],"mappings":"AAAA,SAASA,UAAU,QAAQ,iBAAiB;AAC5C,SAASC,IAAI,EAAEC,MAAM,QAAQ,iBAAiB;AAC9C,SACEC,kBAAkB,EAClBC,uBAAuB,EACvBC,0BAA0B,QACrB,gBAAgB;AAEvB,OAAO,IAAMC,gBAAgB,GAAG,EAAE;AAClC,OAAO,IAAMC,cAAc,GAAG,GAAG;AACjC,IAAMC,kBAAkB,GAAG,EAAE;AAC7B,IAAIC,iBAAiB;AAErB,OAAO,SAASC,6BAA6BA,CAC3CC,UAAU,EACVC,oBAAoB,EAEpB;EAAA,IADAC,eAAe,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC;EAEnB,IAAQG,aAAa,GAAoCL,oBAAoB,CAArEK,aAAa;IAAEC,cAAc,GAAoBN,oBAAoB,CAAtDM,cAAc;IAAEC,aAAa,GAAKP,oBAAoB,CAAtCO,aAAa;EACpD,IAAMC,eAAe,GAAG,SAAlBA,eAAeA,CAAaC,OAAO,EAAE;IACzC,OAAOH,cAAc,CAAChB,MAAM,CAAC,CAAC,CAAC,EAAEmB,OAAO,EAAE;MAAEC,IAAI,EAAEC;IAAY,CAAC,CAAC,CAAC;EACnE,CAAC;EACD,IAAMC,aAAa,GAAG,SAAhBA,aAAaA,CAAA,EAAe;IAChC,IAAMH,OAAO,GAAGT,oB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ignoreList":[]}
1
+ {"version":3,"file":"sessionStoreOperations.js","names":["setTimeout","UUID","assign","ONE_SECOND","timeStampNow","elapsed","expandSessionState","isSessionInExpiredState","addTelemetryDebug","LOCK_RETRY_DELAY","LOCK_MAX_TRIES","LOCK_EXPIRATION_DELAY","LOCK_SEPARATOR","bufferedOperations","ongoingOperations","processSessionStoreOperations","operations","sessionStoreStrategy","numberOfRetries","arguments","length","undefined","isLockEnabled","persistSession","expireSession","persistWithLock","session","lock","currentLock","retrieveStore","_sessionStoreStrategy","retrieveSession","_objectWithoutProperties","_excluded","isLockExpired","push","currentStore","next","retryLater","createLock","processedSession","process","after","sessionStore","currentNumberOfRetries","nextOperations","shift","_lock$split","split","_lock$split2","_slicedToArray","timeStamp","Number"],"sources":["../../src/session/sessionStoreOperations.js"],"sourcesContent":["import { setTimeout } from '../helper/timer'\nimport {\n UUID,\n assign,\n ONE_SECOND,\n timeStampNow,\n elapsed\n} from '../helper/tools'\nimport { expandSessionState, isSessionInExpiredState } from './sessionState'\nimport { addTelemetryDebug } from '../telemetry/telemetry'\nexport const LOCK_RETRY_DELAY = 10\nexport const LOCK_MAX_TRIES = 100\n\n// Locks should be hold for a few milliseconds top, just the time it takes to read and write a\n// cookie. Using one second should be enough in most situations.\nexport const LOCK_EXPIRATION_DELAY = ONE_SECOND\nconst LOCK_SEPARATOR = '--'\nconst bufferedOperations = []\nlet ongoingOperations\n\nexport function processSessionStoreOperations(\n operations,\n sessionStoreStrategy,\n numberOfRetries = 0\n) {\n const { isLockEnabled, persistSession, expireSession } = sessionStoreStrategy\n const persistWithLock = function (session) {\n return persistSession(assign({}, session, { lock: currentLock }))\n }\n const retrieveStore = function () {\n const { lock, ...session } = sessionStoreStrategy.retrieveSession()\n\n return {\n session,\n lock: lock && !isLockExpired(lock) ? lock : undefined\n }\n }\n\n if (!ongoingOperations) {\n ongoingOperations = operations\n }\n if (operations !== ongoingOperations) {\n bufferedOperations.push(operations)\n return\n }\n if (isLockEnabled && numberOfRetries >= LOCK_MAX_TRIES) {\n addTelemetryDebug('Aborted session operation after max lock retries', {\n currentStore: retrieveStore()\n })\n next(sessionStoreStrategy)\n return\n }\n let currentLock\n let currentStore = retrieveStore()\n if (isLockEnabled) {\n // if someone has lock, retry later\n if (currentStore.lock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n // acquire lock\n currentLock = createLock()\n persistWithLock(currentStore.session)\n // if lock is not acquired, retry later\n currentStore = retrieveStore()\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n }\n let processedSession = operations.process(currentStore.session)\n if (isLockEnabled) {\n // if lock corrupted after process, retry later\n currentStore = retrieveStore()\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n }\n if (processedSession) {\n if (isSessionInExpiredState(processedSession)) {\n expireSession()\n } else {\n expandSessionState(processedSession)\n isLockEnabled\n ? persistWithLock(processedSession)\n : persistSession(processedSession)\n }\n }\n if (isLockEnabled) {\n // correctly handle lock around expiration would require to handle this case properly at several levels\n // since we don't have evidence of lock issues around expiration, let's just not do the corruption check for it\n if (!(processedSession && isSessionInExpiredState(processedSession))) {\n // if lock corrupted after persist, retry later\n currentStore = retrieveStore()\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries)\n return\n }\n persistSession(currentStore.session)\n processedSession = currentStore.session\n }\n }\n // call after even if session is not persisted in order to perform operations on\n // up-to-date session state value => the value could have been modified by another tab\n if (operations.after) {\n operations.after(processedSession || currentStore.session)\n }\n next(sessionStoreStrategy)\n}\n\nfunction retryLater(operations, sessionStore, currentNumberOfRetries) {\n setTimeout(function () {\n processSessionStoreOperations(\n operations,\n sessionStore,\n currentNumberOfRetries + 1\n )\n }, LOCK_RETRY_DELAY)\n}\n\nfunction next(sessionStore) {\n ongoingOperations = undefined\n const nextOperations = bufferedOperations.shift()\n if (nextOperations) {\n processSessionStoreOperations(nextOperations, sessionStore)\n }\n}\n\nexport function createLock() {\n return UUID() + LOCK_SEPARATOR + timeStampNow()\n}\n\nfunction isLockExpired(lock) {\n const [, timeStamp] = lock.split(LOCK_SEPARATOR)\n return (\n !timeStamp ||\n elapsed(Number(timeStamp), timeStampNow()) > LOCK_EXPIRATION_DELAY\n )\n}\n"],"mappings":";;;;;;;;;AAAA,SAASA,UAAU,QAAQ,iBAAiB;AAC5C,SACEC,IAAI,EACJC,MAAM,EACNC,UAAU,EACVC,YAAY,EACZC,OAAO,QACF,iBAAiB;AACxB,SAASC,kBAAkB,EAAEC,uBAAuB,QAAQ,gBAAgB;AAC5E,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D,OAAO,IAAMC,gBAAgB,GAAG,EAAE;AAClC,OAAO,IAAMC,cAAc,GAAG,GAAG;;AAEjC;AACA;AACA,OAAO,IAAMC,qBAAqB,GAAGR,UAAU;AAC/C,IAAMS,cAAc,GAAG,IAAI;AAC3B,IAAMC,kBAAkB,GAAG,EAAE;AAC7B,IAAIC,iBAAiB;AAErB,OAAO,SAASC,6BAA6BA,CAC3CC,UAAU,EACVC,oBAAoB,EAEpB;EAAA,IADAC,eAAe,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC;EAEnB,IAAQG,aAAa,GAAoCL,oBAAoB,CAArEK,aAAa;IAAEC,cAAc,GAAoBN,oBAAoB,CAAtDM,cAAc;IAAEC,aAAa,GAAKP,oBAAoB,CAAtCO,aAAa;EACpD,IAAMC,eAAe,GAAG,SAAlBA,eAAeA,CAAaC,OAAO,EAAE;IACzC,OAAOH,cAAc,CAACrB,MAAM,CAAC,CAAC,CAAC,EAAEwB,OAAO,EAAE;MAAEC,IAAI,EAAEC;IAAY,CAAC,CAAC,CAAC;EACnE,CAAC;EACD,IAAMC,aAAa,GAAG,SAAhBA,aAAaA,CAAA,EAAe;IAChC,IAAAC,qBAAA,GAA6Bb,oBAAoB,CAACc,eAAe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AAGhC,kBAAkB,CAACiC,KAAK,CAAC,CAAC;EACjD,IAAID,cAAc,EAAE;IAClB9B,6BAA6B,CAAC8B,cAAc,EAAEF,YAAY,CAAC;EAC7D;AACF;AAEA,OAAO,SAASJ,UAAUA,CAAA,EAAG;EAC3B,OAAOtC,IAAI,CAAC,CAAC,GAAGW,cAAc,GAAGR,YAAY,CAAC,CAAC;AACjD;AAEA,SAAS8B,aAAaA,CAACP,IAAI,EAAE;EAC3B,IAAAoB,WAAA,GAAsBpB,IAAI,CAACqB,KAAK,CAACpC,cAAc,CAAC;IAAAqC,YAAA,GAAAC,cAAA,CAAAH,WAAA;IAAvCI,SAAS,GAAAF,YAAA;EAClB,OACE,CAACE,SAAS,IACV9C,OAAO,CAAC+C,MAAM,CAACD,SAAS,CAAC,EAAE/C,YAAY,CAAC,CAAC,CAAC,GAAGO,qBAAqB;AAEtE","ignoreList":[]}
@@ -232,7 +232,9 @@ function formatPayloadFromEncoder(encoderResult, sendContentTypeByJson) {
232
232
  data: data,
233
233
  type: sendContentTypeByJson ? 'application/json;UTF-8' : undefined,
234
234
  bytesCount: encoderResult.outputBytesCount,
235
- encoding: encoderResult.encoding
235
+ encoding: encoderResult.encoding,
236
+ outputBase64Head: encoderResult.outputBase64Head,
237
+ outputBase64Tail: encoderResult.outputBase64Tail
236
238
  };
237
239
  }
238
240
  //# sourceMappingURL=batch.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"batch.js","names":["display","values","findByPath","each","isNumber","isArray","extend","isString","isEmptyObject","isObject","escapeJsonValue","escapeRowField","escapeRowData","commonTags","dataMap","commonFields","RumEventType","computeBytesCount","isPageExitReason","jsonStringify","CUSTOM_KEYS","processedMessageByDataMap","message","type","rowStr","rowData","undefined","tags","fields","hasFileds","value","key","measurement","tagsStr","filterFileds","value_path","_key","_value","push","fieldsStr","length","_valueData","context","_tagKeys","indexOf","LOGGER","join","date","time","createBatch","options","encoder","request","messageBytesLimit","sendContentTypeByJson","flushController","upsertBuffer","flushSubscription","flushObservable","subscribe","event","flush","getMessageText","messages","isEmpty","arguments","serializedMessage","estimatedMessageBytesCount","notifyBeforeAddMessage","notifyAfterAddMessage","write","realMessageBytesCount","hasMessageFor","remove","removedMessage","messageBytesCount","estimateEncodedBytesCount","notifyAfterRemoveMessage","process","processedMessage","addOrUpdate","warn","concat","upsertMessages","isPageExit","reason","send","sendOnExit","isAsync","encoderResult","finishSync","outputBytesCount","formatPayloadFromEncoder","pendingMessages","pendingData","filter","Boolean","data","bytesCount","text","finish","add","upsert","stop","unsubscribe","output","Blob","encoding"],"sources":["../../src/transport/batch.js"],"sourcesContent":["import { display } from '../helper/display'\nimport {\n values,\n findByPath,\n each,\n isNumber,\n isArray,\n extend,\n isString,\n isEmptyObject,\n isObject\n} from '../helper/tools'\nimport {\n escapeJsonValue,\n escapeRowField,\n escapeRowData\n} from '../helper/serialisation/rowData'\nimport { commonTags, dataMap, commonFields } from '../dataMap'\nimport { RumEventType } from '../helper/enums'\nimport { computeBytesCount } from '../helper/byteUtils'\nimport { isPageExitReason } from '../browser/pageExitObservable'\nimport { jsonStringify } from '../helper/serialisation/jsonStringify'\n// https://en.wikipedia.org/wiki/UTF-8\n// eslint-disable-next-line no-control-regex\nvar CUSTOM_KEYS = 'custom_keys'\nexport var processedMessageByDataMap = function (message) {\n if (!message || !message.type)\n return {\n rowStr: '',\n rowData: undefined\n }\n\n var rowData = { tags: {}, fields: {} }\n var hasFileds = false\n var rowStr = ''\n each(dataMap, function (value, key) {\n if (value.type === message.type) {\n rowStr += key + ','\n rowData.measurement = key\n var tagsStr = []\n var tags = extend({}, commonTags, value.tags)\n var filterFileds = ['date', 'type', CUSTOM_KEYS]\n each(tags, function (value_path, _key) {\n var _value = findByPath(message, value_path)\n filterFileds.push(_key)\n if (_value || isNumber(_value)) {\n rowData.tags[_key] = escapeJsonValue(_value, true)\n tagsStr.push(escapeRowData(_key) + '=' + escapeRowData(_value))\n }\n })\n\n var fieldsStr = []\n var fields = extend({}, commonFields, value.fields)\n each(fields, function (_value, _key) {\n if (isArray(_value) && _value.length === 2) {\n var value_path = _value[1]\n var _valueData = findByPath(message, value_path)\n filterFileds.push(_key)\n if (_valueData !== undefined && _valueData !== null) {\n rowData.fields[_key] = escapeJsonValue(_valueData)\n fieldsStr.push(\n escapeRowData(_key) + '=' + escapeRowField(_valueData)\n )\n }\n } else if (isString(_value)) {\n var _valueData = findByPath(message, _value)\n filterFileds.push(_key)\n if (_valueData !== undefined && _valueData !== null) {\n rowData.fields[_key] = escapeJsonValue(_valueData)\n fieldsStr.push(\n escapeRowData(_key) + '=' + escapeRowField(_valueData)\n )\n }\n }\n })\n if (\n message.context &&\n isObject(message.context) &&\n !isEmptyObject(message.context)\n ) {\n var _tagKeys = []\n each(message.context, function (_value, _key) {\n if (filterFileds.indexOf(_key) > -1) return\n filterFileds.push(_key)\n if (_value !== undefined && _value !== null) {\n _tagKeys.push(_key)\n rowData.fields[_key] = escapeJsonValue(_value)\n fieldsStr.push(escapeRowData(_key) + '=' + escapeRowField(_value))\n }\n })\n if (_tagKeys.length) {\n rowData.fields[CUSTOM_KEYS] = escapeJsonValue(_tagKeys)\n fieldsStr.push(\n escapeRowData(CUSTOM_KEYS) + '=' + escapeRowField(_tagKeys)\n )\n }\n }\n if (message.type === RumEventType.LOGGER) {\n each(message, function (value, key) {\n if (\n filterFileds.indexOf(key) === -1 &&\n value !== undefined &&\n value !== null\n ) {\n rowData.fields[key] = escapeJsonValue(value)\n fieldsStr.push(escapeRowData(key) + '=' + escapeRowField(value))\n }\n })\n }\n if (tagsStr.length) {\n rowStr += tagsStr.join(',')\n }\n if (fieldsStr.length) {\n rowStr += ' '\n rowStr += fieldsStr.join(',')\n hasFileds = true\n }\n rowStr = rowStr + ' ' + message.date\n rowData.time = message.date\n }\n })\n return {\n rowStr: hasFileds ? rowStr : '',\n rowData: hasFileds ? rowData : undefined\n }\n}\n\nexport function createBatch(options) {\n var encoder = options.encoder\n var request = options.request\n var messageBytesLimit = options.messageBytesLimit\n var sendContentTypeByJson = options.sendContentTypeByJson\n var flushController = options.flushController\n var upsertBuffer = {}\n var flushSubscription = flushController.flushObservable.subscribe(function (\n event\n ) {\n flush(event)\n })\n function getMessageText(messages, isEmpty = false) {\n if (sendContentTypeByJson) {\n if (isEmpty) {\n return '[' + messages.join(',')\n } else {\n return ',' + messages.join(',')\n }\n } else {\n if (isEmpty) {\n return messages.join('\\n')\n } else {\n return '\\n' + messages.join('\\n')\n }\n }\n }\n function push(serializedMessage, estimatedMessageBytesCount, key) {\n flushController.notifyBeforeAddMessage(estimatedMessageBytesCount)\n\n if (key !== undefined) {\n upsertBuffer[key] = serializedMessage\n flushController.notifyAfterAddMessage()\n } else {\n encoder.write(\n getMessageText([serializedMessage], encoder.isEmpty()),\n function (realMessageBytesCount) {\n flushController.notifyAfterAddMessage(\n realMessageBytesCount - estimatedMessageBytesCount\n )\n }\n )\n }\n }\n\n function hasMessageFor(key) {\n return key !== undefined && upsertBuffer[key] !== undefined\n }\n\n function remove(key) {\n var removedMessage = upsertBuffer[key]\n delete upsertBuffer[key]\n var messageBytesCount = encoder.estimateEncodedBytesCount(removedMessage)\n flushController.notifyAfterRemoveMessage(messageBytesCount)\n }\n function process(message) {\n var processedMessage = ''\n if (sendContentTypeByJson) {\n processedMessage = jsonStringify(\n processedMessageByDataMap(message).rowData\n )\n } else {\n processedMessage = processedMessageByDataMap(message).rowStr\n }\n return processedMessage\n }\n function addOrUpdate(message, key) {\n const serializedMessage = process(message)\n\n const estimatedMessageBytesCount =\n encoder.estimateEncodedBytesCount(serializedMessage)\n\n if (estimatedMessageBytesCount >= messageBytesLimit) {\n display.warn(\n `Discarded a message whose size was bigger than the maximum allowed size ${messageBytesLimit}KB.`\n )\n return\n }\n\n if (hasMessageFor(key)) {\n remove(key)\n }\n\n push(serializedMessage, estimatedMessageBytesCount, key)\n }\n\n function flush(event) {\n var upsertMessages = values(upsertBuffer).join(\n sendContentTypeByJson ? ',' : '\\n'\n )\n upsertBuffer = {}\n\n var isPageExit = isPageExitReason(event.reason)\n var send = isPageExit ? request.sendOnExit : request.send\n\n if (\n isPageExit &&\n // Note: checking that the encoder is async is not strictly needed, but it's an optimization:\n // if the encoder is async we need to send two requests in some cases (one for encoded data\n // and the other for non-encoded data). But if it's not async, we don't have to worry about\n // it and always send a single request.\n encoder.isAsync\n ) {\n var encoderResult = encoder.finishSync()\n\n // Send encoded messages\n if (encoderResult.outputBytesCount) {\n send(formatPayloadFromEncoder(encoderResult, sendContentTypeByJson))\n }\n\n // Send messages that are not yet encoded at this point\n var pendingMessages = [encoderResult.pendingData, upsertMessages]\n .filter(Boolean)\n .join('\\n')\n\n if (pendingMessages) {\n send({\n data: pendingMessages,\n bytesCount: computeBytesCount(pendingMessages)\n })\n }\n } else {\n if (upsertMessages) {\n var text = getMessageText([upsertMessages], encoder.isEmpty())\n if (sendContentTypeByJson) {\n text += ']'\n }\n encoder.write(text)\n } else {\n if (sendContentTypeByJson) {\n encoder.write(']')\n }\n }\n encoder.finish(function (encoderResult) {\n send(formatPayloadFromEncoder(encoderResult))\n })\n }\n }\n\n return {\n flushController: flushController,\n add: addOrUpdate,\n upsert: addOrUpdate,\n stop: flushSubscription.unsubscribe\n }\n}\n\nfunction formatPayloadFromEncoder(encoderResult, sendContentTypeByJson) {\n var data\n if (typeof encoderResult.output === 'string') {\n data = encoderResult.output\n } else {\n data = new Blob([encoderResult.output], {\n // This will set the 'Content-Type: text/plain' header. Reasoning:\n // * The intake rejects the request if there is no content type.\n // * The browser will issue CORS preflight requests if we set it to 'application/json', which\n // could induce higher intake load (and maybe has other impacts).\n // * Also it's not quite JSON, since we are concatenating multiple JSON objects separated by\n // new lines.\n type: 'text/plain'\n })\n }\n\n return {\n data: data,\n type: sendContentTypeByJson ? 'application/json;UTF-8' : undefined,\n bytesCount: encoderResult.outputBytesCount,\n encoding: encoderResult.encoding\n }\n}\n"],"mappings":"AAAA,SAASA,OAAO,QAAQ,mBAAmB;AAC3C,SACEC,MAAM,EACNC,UAAU,E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,wBAAwB,CAACH,aAAa,CAAC,CAAC;MAC/C,CAAC,CAAC;IACJ;EACF;EAEA,OAAO;IACLlC,eAAe,EAAEA,eAAe;IAChC8C,GAAG,EAAErB,WAAW;IAChBsB,MAAM,EAAEtB,WAAW;IACnBuB,IAAI,EAAE9C,iBAAiB,CAAC+C;EAC1B,CAAC;AACH;AAEA,SAASZ,wBAAwBA,CAACH,aAAa,EAAEnC,qBAAqB,EAAE;EACtE,IAAI2C,IAAI;EACR,IAAI,OAAOR,aAAa,CAACgB,MAAM,KAAK,QAAQ,EAAE;IAC5CR,IAAI,GAAGR,aAAa,CAACgB,MAAM;EAC7B,CAAC,MAAM;IACLR,IAAI,GAAG,IAAIS,IAAI,CAAC,CAACjB,aAAa,CAACgB,MAAM,CAAC,EAAE;MACtC;MACA;MACA;MACA;MACA;MACA;MACAlF,IAAI,EAAE;IACR,CAAC,CAAC;EACJ;EAEA,OAAO;IACL0E,IAAI,EAAEA,IAAI;IACV1E,IAAI,EAAE+B,qBAAqB,GAAG,wBAAwB,GAAG5B,SAAS;IAClEwE,UAAU,EAAET,aAAa,CAACE,gBAAgB;IAC1CgB,QAAQ,EAAElB,aAAa,CAACkB;EAC1B,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"file":"batch.js","names":["display","values","findByPath","each","isNumber","isArray","extend","isString","isEmptyObject","isObject","escapeJsonValue","escapeRowField","escapeRowData","commonTags","dataMap","commonFields","RumEventType","computeBytesCount","isPageExitReason","jsonStringify","CUSTOM_KEYS","processedMessageByDataMap","message","type","rowStr","rowData","undefined","tags","fields","hasFileds","value","key","measurement","tagsStr","filterFileds","value_path","_key","_value","push","fieldsStr","length","_valueData","context","_tagKeys","indexOf","LOGGER","join","date","time","createBatch","options","encoder","request","messageBytesLimit","sendContentTypeByJson","flushController","upsertBuffer","flushSubscription","flushObservable","subscribe","event","flush","getMessageText","messages","isEmpty","arguments","serializedMessage","estimatedMessageBytesCount","notifyBeforeAddMessage","notifyAfterAddMessage","write","realMessageBytesCount","hasMessageFor","remove","removedMessage","messageBytesCount","estimateEncodedBytesCount","notifyAfterRemoveMessage","process","processedMessage","addOrUpdate","warn","concat","upsertMessages","isPageExit","reason","send","sendOnExit","isAsync","encoderResult","finishSync","outputBytesCount","formatPayloadFromEncoder","pendingMessages","pendingData","filter","Boolean","data","bytesCount","text","finish","add","upsert","stop","unsubscribe","output","Blob","encoding","outputBase64Head","outputBase64Tail"],"sources":["../../src/transport/batch.js"],"sourcesContent":["import { display } from '../helper/display'\nimport {\n values,\n findByPath,\n each,\n isNumber,\n isArray,\n extend,\n isString,\n isEmptyObject,\n isObject\n} from '../helper/tools'\nimport {\n escapeJsonValue,\n escapeRowField,\n escapeRowData\n} from '../helper/serialisation/rowData'\nimport { commonTags, dataMap, commonFields } from '../dataMap'\nimport { RumEventType } from '../helper/enums'\nimport { computeBytesCount } from '../helper/byteUtils'\nimport { isPageExitReason } from '../browser/pageExitObservable'\nimport { jsonStringify } from '../helper/serialisation/jsonStringify'\n// https://en.wikipedia.org/wiki/UTF-8\n// eslint-disable-next-line no-control-regex\nvar CUSTOM_KEYS = 'custom_keys'\nexport var processedMessageByDataMap = function (message) {\n if (!message || !message.type)\n return {\n rowStr: '',\n rowData: undefined\n }\n\n var rowData = { tags: {}, fields: {} }\n var hasFileds = false\n var rowStr = ''\n each(dataMap, function (value, key) {\n if (value.type === message.type) {\n rowStr += key + ','\n rowData.measurement = key\n var tagsStr = []\n var tags = extend({}, commonTags, value.tags)\n var filterFileds = ['date', 'type', CUSTOM_KEYS]\n each(tags, function (value_path, _key) {\n var _value = findByPath(message, value_path)\n filterFileds.push(_key)\n if (_value || isNumber(_value)) {\n rowData.tags[_key] = escapeJsonValue(_value, true)\n tagsStr.push(escapeRowData(_key) + '=' + escapeRowData(_value))\n }\n })\n\n var fieldsStr = []\n var fields = extend({}, commonFields, value.fields)\n each(fields, function (_value, _key) {\n if (isArray(_value) && _value.length === 2) {\n var value_path = _value[1]\n var _valueData = findByPath(message, value_path)\n filterFileds.push(_key)\n if (_valueData !== undefined && _valueData !== null) {\n rowData.fields[_key] = escapeJsonValue(_valueData)\n fieldsStr.push(\n escapeRowData(_key) + '=' + escapeRowField(_valueData)\n )\n }\n } else if (isString(_value)) {\n var _valueData = findByPath(message, _value)\n filterFileds.push(_key)\n if (_valueData !== undefined && _valueData !== null) {\n rowData.fields[_key] = escapeJsonValue(_valueData)\n fieldsStr.push(\n escapeRowData(_key) + '=' + escapeRowField(_valueData)\n )\n }\n }\n })\n if (\n message.context &&\n isObject(message.context) &&\n !isEmptyObject(message.context)\n ) {\n var _tagKeys = []\n each(message.context, function (_value, _key) {\n if (filterFileds.indexOf(_key) > -1) return\n filterFileds.push(_key)\n if (_value !== undefined && _value !== null) {\n _tagKeys.push(_key)\n rowData.fields[_key] = escapeJsonValue(_value)\n fieldsStr.push(escapeRowData(_key) + '=' + escapeRowField(_value))\n }\n })\n if (_tagKeys.length) {\n rowData.fields[CUSTOM_KEYS] = escapeJsonValue(_tagKeys)\n fieldsStr.push(\n escapeRowData(CUSTOM_KEYS) + '=' + escapeRowField(_tagKeys)\n )\n }\n }\n if (message.type === RumEventType.LOGGER) {\n each(message, function (value, key) {\n if (\n filterFileds.indexOf(key) === -1 &&\n value !== undefined &&\n value !== null\n ) {\n rowData.fields[key] = escapeJsonValue(value)\n fieldsStr.push(escapeRowData(key) + '=' + escapeRowField(value))\n }\n })\n }\n if (tagsStr.length) {\n rowStr += tagsStr.join(',')\n }\n if (fieldsStr.length) {\n rowStr += ' '\n rowStr += fieldsStr.join(',')\n hasFileds = true\n }\n rowStr = rowStr + ' ' + message.date\n rowData.time = message.date\n }\n })\n return {\n rowStr: hasFileds ? rowStr : '',\n rowData: hasFileds ? rowData : undefined\n }\n}\n\nexport function createBatch(options) {\n var encoder = options.encoder\n var request = options.request\n var messageBytesLimit = options.messageBytesLimit\n var sendContentTypeByJson = options.sendContentTypeByJson\n var flushController = options.flushController\n var upsertBuffer = {}\n var flushSubscription = flushController.flushObservable.subscribe(function (\n event\n ) {\n flush(event)\n })\n function getMessageText(messages, isEmpty = false) {\n if (sendContentTypeByJson) {\n if (isEmpty) {\n return '[' + messages.join(',')\n } else {\n return ',' + messages.join(',')\n }\n } else {\n if (isEmpty) {\n return messages.join('\\n')\n } else {\n return '\\n' + messages.join('\\n')\n }\n }\n }\n function push(serializedMessage, estimatedMessageBytesCount, key) {\n flushController.notifyBeforeAddMessage(estimatedMessageBytesCount)\n\n if (key !== undefined) {\n upsertBuffer[key] = serializedMessage\n flushController.notifyAfterAddMessage()\n } else {\n encoder.write(\n getMessageText([serializedMessage], encoder.isEmpty()),\n function (realMessageBytesCount) {\n flushController.notifyAfterAddMessage(\n realMessageBytesCount - estimatedMessageBytesCount\n )\n }\n )\n }\n }\n\n function hasMessageFor(key) {\n return key !== undefined && upsertBuffer[key] !== undefined\n }\n\n function remove(key) {\n var removedMessage = upsertBuffer[key]\n delete upsertBuffer[key]\n var messageBytesCount = encoder.estimateEncodedBytesCount(removedMessage)\n flushController.notifyAfterRemoveMessage(messageBytesCount)\n }\n function process(message) {\n var processedMessage = ''\n if (sendContentTypeByJson) {\n processedMessage = jsonStringify(\n processedMessageByDataMap(message).rowData\n )\n } else {\n processedMessage = processedMessageByDataMap(message).rowStr\n }\n return processedMessage\n }\n function addOrUpdate(message, key) {\n const serializedMessage = process(message)\n\n const estimatedMessageBytesCount =\n encoder.estimateEncodedBytesCount(serializedMessage)\n\n if (estimatedMessageBytesCount >= messageBytesLimit) {\n display.warn(\n `Discarded a message whose size was bigger than the maximum allowed size ${messageBytesLimit}KB.`\n )\n return\n }\n\n if (hasMessageFor(key)) {\n remove(key)\n }\n\n push(serializedMessage, estimatedMessageBytesCount, key)\n }\n\n function flush(event) {\n var upsertMessages = values(upsertBuffer).join(\n sendContentTypeByJson ? ',' : '\\n'\n )\n upsertBuffer = {}\n\n var isPageExit = isPageExitReason(event.reason)\n var send = isPageExit ? request.sendOnExit : request.send\n\n if (\n isPageExit &&\n // Note: checking that the encoder is async is not strictly needed, but it's an optimization:\n // if the encoder is async we need to send two requests in some cases (one for encoded data\n // and the other for non-encoded data). But if it's not async, we don't have to worry about\n // it and always send a single request.\n encoder.isAsync\n ) {\n var encoderResult = encoder.finishSync()\n\n // Send encoded messages\n if (encoderResult.outputBytesCount) {\n send(formatPayloadFromEncoder(encoderResult, sendContentTypeByJson))\n }\n\n // Send messages that are not yet encoded at this point\n var pendingMessages = [encoderResult.pendingData, upsertMessages]\n .filter(Boolean)\n .join('\\n')\n\n if (pendingMessages) {\n send({\n data: pendingMessages,\n bytesCount: computeBytesCount(pendingMessages)\n })\n }\n } else {\n if (upsertMessages) {\n var text = getMessageText([upsertMessages], encoder.isEmpty())\n if (sendContentTypeByJson) {\n text += ']'\n }\n encoder.write(text)\n } else {\n if (sendContentTypeByJson) {\n encoder.write(']')\n }\n }\n encoder.finish(function (encoderResult) {\n send(formatPayloadFromEncoder(encoderResult))\n })\n }\n }\n\n return {\n flushController: flushController,\n add: addOrUpdate,\n upsert: addOrUpdate,\n stop: flushSubscription.unsubscribe\n }\n}\n\nfunction formatPayloadFromEncoder(encoderResult, sendContentTypeByJson) {\n var data\n if (typeof encoderResult.output === 'string') {\n data = encoderResult.output\n } else {\n data = new Blob([encoderResult.output], {\n // This will set the 'Content-Type: text/plain' header. Reasoning:\n // * The intake rejects the request if there is no content type.\n // * The browser will issue CORS preflight requests if we set it to 'application/json', which\n // could induce higher intake load (and maybe has other impacts).\n // * Also it's not quite JSON, since we are concatenating multiple JSON objects separated by\n // new lines.\n type: 'text/plain'\n })\n }\n\n return {\n data: data,\n type: sendContentTypeByJson ? 'application/json;UTF-8' : undefined,\n bytesCount: encoderResult.outputBytesCount,\n encoding: encoderResult.encoding,\n outputBase64Head: encoderResult.outputBase64Head,\n outputBase64Tail: encoderResult.outputBase64Tail\n }\n}\n"],"mappings":"AAAA,SAASA,OAAO,QAAQ,mBAAmB;AAC3C,SACEC,MAAM,EACNC,UAAU,EACVC,IAAI,EACJC,QAAQ,EAC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,CAAC;MAC/C,CAAC,CAAC;IACJ;EACF;EAEA,OAAO;IACLlC,eAAe,EAAEA,eAAe;IAChC8C,GAAG,EAAErB,WAAW;IAChBsB,MAAM,EAAEtB,WAAW;IACnBuB,IAAI,EAAE9C,iBAAiB,CAAC+C;EAC1B,CAAC;AACH;AAEA,SAASZ,wBAAwBA,CAACH,aAAa,EAAEnC,qBAAqB,EAAE;EACtE,IAAI2C,IAAI;EACR,IAAI,OAAOR,aAAa,CAACgB,MAAM,KAAK,QAAQ,EAAE;IAC5CR,IAAI,GAAGR,aAAa,CAACgB,MAAM;EAC7B,CAAC,MAAM;IACLR,IAAI,GAAG,IAAIS,IAAI,CAAC,CAACjB,aAAa,CAACgB,MAAM,CAAC,EAAE;MACtC;MACA;MACA;MACA;MACA;MACA;MACAlF,IAAI,EAAE;IACR,CAAC,CAAC;EACJ;EAEA,OAAO;IACL0E,IAAI,EAAEA,IAAI;IACV1E,IAAI,EAAE+B,qBAAqB,GAAG,wBAAwB,GAAG5B,SAAS;IAClEwE,UAAU,EAAET,aAAa,CAACE,gBAAgB;IAC1CgB,QAAQ,EAAElB,aAAa,CAACkB,QAAQ;IAChCC,gBAAgB,EAAEnB,aAAa,CAACmB,gBAAgB;IAChDC,gBAAgB,EAAEpB,aAAa,CAACoB;EAClC,CAAC;AACH","ignoreList":[]}
@@ -83,10 +83,18 @@ export function fetchKeepAliveStrategy(endpointUrl, bytesLimit, payload, onRespo
83
83
  keepalive: true,
84
84
  mode: 'cors'
85
85
  };
86
+ var headers = {};
86
87
  if (payload.type) {
87
- fetchOption.headers = {
88
- 'Content-Type': payload.type
89
- };
88
+ headers['Content-Type'] = payload.type;
89
+ }
90
+ if (payload.outputBase64Head) {
91
+ headers['x-base64-head'] = payload.outputBase64Head;
92
+ }
93
+ if (payload.outputBase64Tail) {
94
+ headers['x-base64-tail'] = payload.outputBase64Tail;
95
+ }
96
+ if (Object.keys(headers).length) {
97
+ fetchOption.headers = headers;
90
98
  }
91
99
  fetch(url, fetchOption).then(monitor(function (response) {
92
100
  if (typeof onResponse === 'function') {
@@ -95,9 +103,8 @@ export function fetchKeepAliveStrategy(endpointUrl, bytesLimit, payload, onRespo
95
103
  type: response.type
96
104
  });
97
105
  }
98
- }), monitor(function () {
99
- // failed to queue the request
100
- sendXHR(url, payload, onResponse);
106
+ }))["catch"](monitor(function () {
107
+ fetchStrategy(url, payload, onResponse);
101
108
  }));
102
109
  } else {
103
110
  sendXHR(url, payload, onResponse);
@@ -131,4 +138,31 @@ function sendXHR(url, payload, onResponse) {
131
138
  });
132
139
  request.send(data);
133
140
  }
141
+ function fetchStrategy(url, payload, onResponse) {
142
+ var fetchOption = {
143
+ method: 'POST',
144
+ body: payload.data,
145
+ keepalive: true,
146
+ mode: 'cors'
147
+ };
148
+ if (payload.type) {
149
+ fetchOption.headers = {
150
+ 'Content-Type': payload.type
151
+ };
152
+ }
153
+ fetch(url, fetchOption).then(monitor(function (response) {
154
+ if (typeof onResponse === 'function') {
155
+ onResponse({
156
+ status: response.status,
157
+ type: response.type
158
+ });
159
+ }
160
+ }))["catch"](monitor(function () {
161
+ if (typeof onResponse === 'function') {
162
+ onResponse({
163
+ status: 0
164
+ });
165
+ }
166
+ }));
167
+ }
134
168
  //# sourceMappingURL=httpRequest.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"httpRequest.js","names":["newRetryState","sendWithRetryStrategy","addEventListener","monitor","addTelemetryError","addBatchPrecision","url","encoding","indexOf","createHttpRequest","endpointUrl","bytesLimit","retryMaxSize","reportError","undefined","retryState","sendStrategyForRetry","payload","onResponse","fetchKeepAliveStrategy","send","sendOnExit","sendBeaconStrategy","data","bytesCount","canUseBeacon","navigator","sendBeacon","beaconData","type","Blob","isQueued","e","reportBeaconError","sendXHR","hasReportedBeaconError","canUseKeepAlive","isKeepAliveSupported","fetchOption","method","body","keepalive","mode","headers","fetch","then","response","status","window","Request","_unused","request","XMLHttpRequest","open","setRequestHeader","once"],"sources":["../../src/transport/httpRequest.js"],"sourcesContent":["import { newRetryState, sendWithRetryStrategy } from './sendWithRetryStrategy'\nimport { addEventListener } from '../browser/addEventListener'\nimport { monitor } from '../helper/monitor'\nimport { addTelemetryError } from '../telemetry/telemetry'\n/**\n * Use POST request without content type to:\n * - avoid CORS preflight requests\n * - allow usage of sendBeacon\n *\n * multiple elements are sent separated by \\n in order\n * to be parsed correctly without content type header\n */\nfunction addBatchPrecision(url, encoding) {\n if (!url) return url\n url = url + (url.indexOf('?') === -1 ? '?' : '&') + 'precision=ms'\n if (encoding) {\n url = url + '&encoding=' + encoding\n }\n return url\n}\nexport function createHttpRequest(\n endpointUrl,\n bytesLimit,\n retryMaxSize,\n reportError\n) {\n if (retryMaxSize === undefined) {\n retryMaxSize = -1\n }\n var retryState = newRetryState(retryMaxSize)\n var sendStrategyForRetry = function (payload, onResponse) {\n return fetchKeepAliveStrategy(endpointUrl, bytesLimit, payload, onResponse)\n }\n\n return {\n send: function (payload) {\n sendWithRetryStrategy(\n payload,\n retryState,\n sendStrategyForRetry,\n endpointUrl,\n reportError\n )\n },\n /**\n * Since fetch keepalive behaves like regular fetch on Firefox,\n * keep using sendBeaconStrategy on exit\n */\n sendOnExit: function (payload) {\n sendBeaconStrategy(endpointUrl, bytesLimit, payload)\n }\n }\n}\n\nfunction sendBeaconStrategy(endpointUrl, bytesLimit, payload) {\n var data = payload.data\n var bytesCount = payload.bytesCount\n var url = addBatchPrecision(endpointUrl, payload.encoding)\n var canUseBeacon = !!navigator.sendBeacon && bytesCount < bytesLimit\n if (canUseBeacon) {\n try {\n var beaconData\n if (payload.type) {\n beaconData = new Blob([data], {\n type: payload.type\n })\n } else {\n beaconData = data\n }\n\n var isQueued = navigator.sendBeacon(url, beaconData)\n\n if (isQueued) {\n return\n }\n } catch (e) {\n reportBeaconError(e)\n }\n }\n sendXHR(url, payload)\n}\nvar hasReportedBeaconError = false\n\nfunction reportBeaconError(e) {\n if (!hasReportedBeaconError) {\n hasReportedBeaconError = true\n addTelemetryError(e)\n }\n}\nexport function fetchKeepAliveStrategy(\n endpointUrl,\n bytesLimit,\n payload,\n onResponse\n) {\n var data = payload.data\n var bytesCount = payload.bytesCount\n var url = addBatchPrecision(endpointUrl, payload.encoding)\n var canUseKeepAlive = isKeepAliveSupported() && bytesCount < bytesLimit\n if (canUseKeepAlive) {\n var fetchOption = {\n method: 'POST',\n body: data,\n keepalive: true,\n mode: 'cors'\n }\n if (payload.type) {\n fetchOption.headers = {\n 'Content-Type': payload.type\n }\n }\n fetch(url, fetchOption).then(\n monitor(function (response) {\n if (typeof onResponse === 'function') {\n onResponse({ status: response.status, type: response.type })\n }\n }),\n monitor(function () {\n // failed to queue the request\n sendXHR(url, payload, onResponse)\n })\n )\n } else {\n sendXHR(url, payload, onResponse)\n }\n}\n\nfunction isKeepAliveSupported() {\n // Request can throw, cf https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#errors\n try {\n return window.Request && 'keepalive' in new Request('http://a')\n } catch {\n return false\n }\n}\n\nfunction sendXHR(url, payload, onResponse) {\n const data = payload.data\n const request = new XMLHttpRequest()\n request.open('POST', url, true)\n if (data instanceof Blob) {\n request.setRequestHeader('Content-Type', data.type)\n } else if (payload.type) {\n request.setRequestHeader('Content-Type', payload.type)\n }\n\n addEventListener(\n request,\n 'loadend',\n function () {\n if (typeof onResponse === 'function') {\n onResponse({ status: request.status })\n }\n },\n {\n once: true\n }\n )\n request.send(data)\n}\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,qBAAqB,QAAQ,yBAAyB;AAC9E,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SAASC,OAAO,QAAQ,mBAAmB;AAC3C,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,iBAAiBA,CAACC,GAAG,EAAEC,QAAQ,EAAE;EACxC,IAAI,CAACD,GAAG,EAAE,OAAOA,GAAG;EACpBA,GAAG,GAAGA,GAAG,IAAIA,GAAG,CAACE,OAAO,CAAC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YAAY;IACV,IAAI,OAAOjC,UAAU,KAAK,UAAU,EAAE;MACpCA,UAAU,CAAC;QAAE6B,MAAM,EAAEI,OAAO,CAACJ;MAAO,CAAC,CAAC;IACxC;EACF,CAAC,EACD;IACEQ,IAAI,EAAE;EACR,CACF,CAAC;EACDJ,OAAO,CAAC/B,IAAI,CAACG,IAAI,CAAC;AACpB","ignoreList":[]}
1
+ {"version":3,"file":"httpRequest.js","names":["newRetryState","sendWithRetryStrategy","addEventListener","monitor","addTelemetryError","addBatchPrecision","url","encoding","indexOf","createHttpRequest","endpointUrl","bytesLimit","retryMaxSize","reportError","undefined","retryState","sendStrategyForRetry","payload","onResponse","fetchKeepAliveStrategy","send","sendOnExit","sendBeaconStrategy","data","bytesCount","canUseBeacon","navigator","sendBeacon","beaconData","type","Blob","isQueued","e","reportBeaconError","sendXHR","hasReportedBeaconError","canUseKeepAlive","isKeepAliveSupported","fetchOption","method","body","keepalive","mode","headers","outputBase64Head","outputBase64Tail","Object","keys","length","fetch","then","response","status","fetchStrategy","window","Request","_unused","request","XMLHttpRequest","open","setRequestHeader","once"],"sources":["../../src/transport/httpRequest.js"],"sourcesContent":["import { newRetryState, sendWithRetryStrategy } from './sendWithRetryStrategy'\nimport { addEventListener } from '../browser/addEventListener'\nimport { monitor } from '../helper/monitor'\nimport { addTelemetryError } from '../telemetry/telemetry'\n/**\n * Use POST request without content type to:\n * - avoid CORS preflight requests\n * - allow usage of sendBeacon\n *\n * multiple elements are sent separated by \\n in order\n * to be parsed correctly without content type header\n */\nfunction addBatchPrecision(url, encoding) {\n if (!url) return url\n url = url + (url.indexOf('?') === -1 ? '?' : '&') + 'precision=ms'\n if (encoding) {\n url = url + '&encoding=' + encoding\n }\n return url\n}\nexport function createHttpRequest(\n endpointUrl,\n bytesLimit,\n retryMaxSize,\n reportError\n) {\n if (retryMaxSize === undefined) {\n retryMaxSize = -1\n }\n var retryState = newRetryState(retryMaxSize)\n var sendStrategyForRetry = function (payload, onResponse) {\n return fetchKeepAliveStrategy(endpointUrl, bytesLimit, payload, onResponse)\n }\n\n return {\n send: function (payload) {\n sendWithRetryStrategy(\n payload,\n retryState,\n sendStrategyForRetry,\n endpointUrl,\n reportError\n )\n },\n /**\n * Since fetch keepalive behaves like regular fetch on Firefox,\n * keep using sendBeaconStrategy on exit\n */\n sendOnExit: function (payload) {\n sendBeaconStrategy(endpointUrl, bytesLimit, payload)\n }\n }\n}\n\nfunction sendBeaconStrategy(endpointUrl, bytesLimit, payload) {\n var data = payload.data\n var bytesCount = payload.bytesCount\n var url = addBatchPrecision(endpointUrl, payload.encoding)\n var canUseBeacon = !!navigator.sendBeacon && bytesCount < bytesLimit\n if (canUseBeacon) {\n try {\n var beaconData\n if (payload.type) {\n beaconData = new Blob([data], {\n type: payload.type\n })\n } else {\n beaconData = data\n }\n\n var isQueued = navigator.sendBeacon(url, beaconData)\n\n if (isQueued) {\n return\n }\n } catch (e) {\n reportBeaconError(e)\n }\n }\n sendXHR(url, payload)\n}\nvar hasReportedBeaconError = false\n\nfunction reportBeaconError(e) {\n if (!hasReportedBeaconError) {\n hasReportedBeaconError = true\n addTelemetryError(e)\n }\n}\nexport function fetchKeepAliveStrategy(\n endpointUrl,\n bytesLimit,\n payload,\n onResponse\n) {\n var data = payload.data\n var bytesCount = payload.bytesCount\n var url = addBatchPrecision(endpointUrl, payload.encoding)\n var canUseKeepAlive = isKeepAliveSupported() && bytesCount < bytesLimit\n if (canUseKeepAlive) {\n var fetchOption = {\n method: 'POST',\n body: data,\n keepalive: true,\n mode: 'cors'\n }\n const headers = {}\n\n if (payload.type) {\n headers['Content-Type'] = payload.type\n }\n if (payload.outputBase64Head) {\n headers['x-base64-head'] = payload.outputBase64Head\n }\n if (payload.outputBase64Tail) {\n headers['x-base64-tail'] = payload.outputBase64Tail\n }\n if (Object.keys(headers).length) {\n fetchOption.headers = headers\n }\n fetch(url, fetchOption)\n .then(\n monitor(function (response) {\n if (typeof onResponse === 'function') {\n onResponse({ status: response.status, type: response.type })\n }\n })\n )\n .catch(\n monitor(function () {\n fetchStrategy(url, payload, onResponse)\n })\n )\n } else {\n sendXHR(url, payload, onResponse)\n }\n}\n\nfunction isKeepAliveSupported() {\n // Request can throw, cf https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#errors\n try {\n return window.Request && 'keepalive' in new Request('http://a')\n } catch {\n return false\n }\n}\n\nfunction sendXHR(url, payload, onResponse) {\n const data = payload.data\n const request = new XMLHttpRequest()\n request.open('POST', url, true)\n if (data instanceof Blob) {\n request.setRequestHeader('Content-Type', data.type)\n } else if (payload.type) {\n request.setRequestHeader('Content-Type', payload.type)\n }\n\n addEventListener(\n request,\n 'loadend',\n function () {\n if (typeof onResponse === 'function') {\n onResponse({ status: request.status })\n }\n },\n {\n once: true\n }\n )\n request.send(data)\n}\nfunction fetchStrategy(url, payload, onResponse) {\n const fetchOption = {\n method: 'POST',\n body: payload.data,\n keepalive: true,\n mode: 'cors'\n }\n if (payload.type) {\n fetchOption.headers = {\n 'Content-Type': payload.type\n }\n }\n fetch(url, fetchOption)\n .then(\n monitor(function (response) {\n if (typeof onResponse === 'function') {\n onResponse({ status: response.status, type: response.type })\n }\n })\n )\n .catch(\n monitor(function () {\n if (typeof onResponse === 'function') {\n onResponse({ status: 0 })\n }\n })\n )\n}\n"],"mappings":"AAAA,SAASA,aAAa,EAAEC,qBAAqB,QAAQ,yBAAyB;AAC9E,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SAASC,OAAO,QAAQ,mBAAmB;AAC3C,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,iBAAiBA,CAACC,GAAG,EAAEC,QAAQ,EAAE;EACxC,IAAI,CAACD,GAAG,EAAE,OAAOA,GAAG;EACpBA,GAAG,GAAGA,GAAG,IAAIA,GAAG,CAACE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,cAAc;E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QAAEkC,MAAM,EAAE;MAAE,CAAC,CAAC;IAC3B;EACF,CAAC,CACH,CAAC;AACL","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudcare/browser-core",
3
- "version": "3.2.28",
3
+ "version": "3.2.29",
4
4
  "main": "cjs/index.js",
5
5
  "module": "esm/index.js",
6
6
  "types": "types/index.d.ts",
@@ -21,5 +21,5 @@
21
21
  },
22
22
  "author": "dataflux",
23
23
  "license": "MIT",
24
- "gitHead": "1d42bf528926c2c13947c3298a1d18ea2a4e91f6"
24
+ "gitHead": "c00a63dc2a909293f5001ed01ed11ce1d92383df"
25
25
  }
package/src/dataMap.js CHANGED
@@ -58,6 +58,7 @@ export var dataMap = {
58
58
  view_privacy_replay_level: 'privacy.replay_level'
59
59
  },
60
60
  fields: {
61
+ view_update_time: '_gc.view_update_time',
61
62
  sampled_for_replay: 'session.sampled_for_replay',
62
63
  sampled_for_error_replay: 'session.sampled_for_error_replay',
63
64
  sampled_for_error_session: 'session.sampled_for_error_session',
package/src/index.js CHANGED
@@ -45,7 +45,8 @@ export {
45
45
  } from './session/sessionManagement'
46
46
  export {
47
47
  SESSION_TIME_OUT_DELAY,
48
- SESSION_STORE_KEY
48
+ SESSION_STORE_KEY,
49
+ SessionPersistence
49
50
  } from './session/sessionConstants'
50
51
  export { STORAGE_POLL_DELAY } from './session/sessionStore'
51
52
  export * from './transport'
@@ -2,3 +2,7 @@ import { ONE_HOUR, ONE_MINUTE } from '../helper/tools'
2
2
  export var SESSION_TIME_OUT_DELAY = 4 * ONE_HOUR
3
3
  export var SESSION_EXPIRATION_DELAY = 15 * ONE_MINUTE
4
4
  export var SESSION_STORE_KEY = '_gc_s'
5
+ export const SessionPersistence = {
6
+ COOKIE: 'cookie',
7
+ LOCAL_STORAGE: 'local-storage'
8
+ }
@@ -8,7 +8,8 @@ import {
8
8
  import {
9
9
  SESSION_EXPIRATION_DELAY,
10
10
  SESSION_TIME_OUT_DELAY,
11
- SESSION_STORE_KEY
11
+ SESSION_STORE_KEY,
12
+ SessionPersistence
12
13
  } from './sessionConstants'
13
14
  import {
14
15
  toSessionString,
@@ -19,7 +20,7 @@ import {
19
20
  export function selectCookieStrategy(initConfiguration) {
20
21
  const cookieOptions = buildCookieOptions(initConfiguration)
21
22
  return areCookiesAuthorized(cookieOptions)
22
- ? { type: 'Cookie', cookieOptions }
23
+ ? { type: SessionPersistence.COOKIE, cookieOptions }
23
24
  : undefined
24
25
  }
25
26
 
@@ -5,7 +5,7 @@ import {
5
5
  getExpiredSessionState
6
6
  } from './sessionState'
7
7
 
8
- import { SESSION_STORE_KEY } from './sessionConstants'
8
+ import { SESSION_STORE_KEY, SessionPersistence } from './sessionConstants'
9
9
 
10
10
  const LOCAL_STORAGE_TEST_KEY = '_gc_test_'
11
11
 
@@ -16,7 +16,9 @@ export function selectLocalStorageStrategy() {
16
16
  localStorage.setItem(testKey, id)
17
17
  const retrievedId = localStorage.getItem(testKey)
18
18
  localStorage.removeItem(testKey)
19
- return id === retrievedId ? { type: 'LocalStorage' } : undefined
19
+ return id === retrievedId
20
+ ? { type: SessionPersistence.LOCAL_STORAGE }
21
+ : undefined
20
22
  } catch (e) {
21
23
  return undefined
22
24
  }
@@ -1,5 +1,6 @@
1
1
  import { clearInterval, setInterval } from '../helper/timer'
2
2
  import { Observable } from '../helper/observable'
3
+ import { display } from '../helper/display'
3
4
  import { ONE_SECOND, dateNow, throttle, UUID, assign } from '../helper/tools'
4
5
  import { selectCookieStrategy, initCookieStrategy } from './sessionInCookie'
5
6
  import {
@@ -13,6 +14,7 @@ import {
13
14
  selectLocalStorageStrategy
14
15
  } from './sessionInLocalStorage'
15
16
  import { processSessionStoreOperations } from './sessionStoreOperations'
17
+ import { SessionPersistence } from './sessionConstants'
16
18
 
17
19
  /**
18
20
  * Every second, the storage will be polled to check for any change that can occur
@@ -26,14 +28,31 @@ export const STORAGE_POLL_DELAY = ONE_SECOND
26
28
  * Else, checks if LocalStorage is allowed and available
27
29
  */
28
30
  export function selectSessionStoreStrategyType(initConfiguration) {
29
- let sessionStoreStrategyType = selectCookieStrategy(initConfiguration)
30
- if (
31
- !sessionStoreStrategyType &&
32
- initConfiguration.allowFallbackToLocalStorage
33
- ) {
34
- sessionStoreStrategyType = selectLocalStorageStrategy()
31
+ switch (initConfiguration.sessionPersistence) {
32
+ case SessionPersistence.COOKIE:
33
+ return selectCookieStrategy(initConfiguration)
34
+
35
+ case SessionPersistence.LOCAL_STORAGE:
36
+ return selectLocalStorageStrategy()
37
+
38
+ case undefined: {
39
+ let sessionStoreStrategyType = selectCookieStrategy(initConfiguration)
40
+ if (
41
+ !sessionStoreStrategyType &&
42
+ initConfiguration.allowFallbackToLocalStorage
43
+ ) {
44
+ sessionStoreStrategyType = selectLocalStorageStrategy()
45
+ }
46
+ return sessionStoreStrategyType
47
+ }
48
+
49
+ default:
50
+ display.error(
51
+ `Invalid session persistence '${String(
52
+ initConfiguration.sessionPersistence
53
+ )}'`
54
+ )
35
55
  }
36
- return sessionStoreStrategyType
37
56
  }
38
57
 
39
58
  /**
@@ -51,7 +70,7 @@ export function startSessionStore(
51
70
  const expireObservable = new Observable()
52
71
  const sessionStateUpdateObservable = new Observable()
53
72
  const sessionStoreStrategy =
54
- sessionStoreStrategyType.type === 'Cookie'
73
+ sessionStoreStrategyType.type === SessionPersistence.COOKIE
55
74
  ? initCookieStrategy(sessionStoreStrategyType.cookieOptions)
56
75
  : initLocalStorageStrategy()
57
76
  const { expireSession } = sessionStoreStrategy
@@ -1,13 +1,20 @@
1
1
  import { setTimeout } from '../helper/timer'
2
- import { UUID, assign } from '../helper/tools'
3
2
  import {
4
- expandSessionState,
5
- isSessionInExpiredState,
6
- isSessionInNotStartedState
7
- } from './sessionState'
8
-
3
+ UUID,
4
+ assign,
5
+ ONE_SECOND,
6
+ timeStampNow,
7
+ elapsed
8
+ } from '../helper/tools'
9
+ import { expandSessionState, isSessionInExpiredState } from './sessionState'
10
+ import { addTelemetryDebug } from '../telemetry/telemetry'
9
11
  export const LOCK_RETRY_DELAY = 10
10
12
  export const LOCK_MAX_TRIES = 100
13
+
14
+ // Locks should be hold for a few milliseconds top, just the time it takes to read and write a
15
+ // cookie. Using one second should be enough in most situations.
16
+ export const LOCK_EXPIRATION_DELAY = ONE_SECOND
17
+ const LOCK_SEPARATOR = '--'
11
18
  const bufferedOperations = []
12
19
  let ongoingOperations
13
20
 
@@ -21,15 +28,11 @@ export function processSessionStoreOperations(
21
28
  return persistSession(assign({}, session, { lock: currentLock }))
22
29
  }
23
30
  const retrieveStore = function () {
24
- const session = sessionStoreStrategy.retrieveSession()
25
- const lock = session.lock
26
- if (session.lock) {
27
- delete session.lock
28
- }
31
+ const { lock, ...session } = sessionStoreStrategy.retrieveSession()
29
32
 
30
33
  return {
31
34
  session,
32
- lock
35
+ lock: lock && !isLockExpired(lock) ? lock : undefined
33
36
  }
34
37
  }
35
38
 
@@ -41,6 +44,9 @@ export function processSessionStoreOperations(
41
44
  return
42
45
  }
43
46
  if (isLockEnabled && numberOfRetries >= LOCK_MAX_TRIES) {
47
+ addTelemetryDebug('Aborted session operation after max lock retries', {
48
+ currentStore: retrieveStore()
49
+ })
44
50
  next(sessionStoreStrategy)
45
51
  return
46
52
  }
@@ -53,7 +59,7 @@ export function processSessionStoreOperations(
53
59
  return
54
60
  }
55
61
  // acquire lock
56
- currentLock = UUID()
62
+ currentLock = createLock()
57
63
  persistWithLock(currentStore.session)
58
64
  // if lock is not acquired, retry later
59
65
  currentStore = retrieveStore()
@@ -120,3 +126,15 @@ function next(sessionStore) {
120
126
  processSessionStoreOperations(nextOperations, sessionStore)
121
127
  }
122
128
  }
129
+
130
+ export function createLock() {
131
+ return UUID() + LOCK_SEPARATOR + timeStampNow()
132
+ }
133
+
134
+ function isLockExpired(lock) {
135
+ const [, timeStamp] = lock.split(LOCK_SEPARATOR)
136
+ return (
137
+ !timeStamp ||
138
+ elapsed(Number(timeStamp), timeStampNow()) > LOCK_EXPIRATION_DELAY
139
+ )
140
+ }
@@ -292,6 +292,8 @@ function formatPayloadFromEncoder(encoderResult, sendContentTypeByJson) {
292
292
  data: data,
293
293
  type: sendContentTypeByJson ? 'application/json;UTF-8' : undefined,
294
294
  bytesCount: encoderResult.outputBytesCount,
295
- encoding: encoderResult.encoding
295
+ encoding: encoderResult.encoding,
296
+ outputBase64Head: encoderResult.outputBase64Head,
297
+ outputBase64Tail: encoderResult.outputBase64Tail
296
298
  }
297
299
  }