@allthings/sdk 5.0.3 → 5.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,8 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- Object.defineProperty(exports, '__esModule', { value: true });
5
-
6
4
  var querystring = require('query-string');
7
5
  var fetch = require('cross-fetch');
8
6
  var Bottleneck = require('bottleneck');
@@ -14,20 +12,7 @@ var https = require('https');
14
12
  var url = require('url');
15
13
  var fs = require('fs');
16
14
 
17
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
18
-
19
- var querystring__default = /*#__PURE__*/_interopDefaultLegacy(querystring);
20
- var fetch__default = /*#__PURE__*/_interopDefaultLegacy(fetch);
21
- var Bottleneck__default = /*#__PURE__*/_interopDefaultLegacy(Bottleneck);
22
- var util__default = /*#__PURE__*/_interopDefaultLegacy(util);
23
- var stream__default = /*#__PURE__*/_interopDefaultLegacy(stream);
24
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
25
- var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
26
- var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
27
- var url__default = /*#__PURE__*/_interopDefaultLegacy(url);
28
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
29
-
30
- const version = "5.0.3";
15
+ const version = "5.0.4";
31
16
 
32
17
  const REST_API_URL = 'https://api.allthings.me';
33
18
  const OAUTH_URL = 'https://accounts.allthings.me';
@@ -70,7 +55,7 @@ const isEligibleForClientRedirect$1 = (params) => {
70
55
  return false;
71
56
  }
72
57
  };
73
- const getRedirectUrl$1 = (params) => `${params.oauthUrl}/oauth/authorize?${querystring__default["default"].stringify(castToAuthorizationRequestParams$1(params), {
58
+ const getRedirectUrl$1 = (params) => `${params.oauthUrl}/oauth/authorize?${querystring.stringify(castToAuthorizationRequestParams$1(params), {
74
59
  skipNull: true,
75
60
  skipEmptyString: true,
76
61
  })}`;
@@ -123,8 +108,8 @@ function makeLogger(name) {
123
108
  const logger = makeLogger('OAuth Token Request');
124
109
  const makeFetchTokenRequester = (url) => async (params) => {
125
110
  try {
126
- const response = await fetch__default["default"](url, {
127
- body: querystring__default["default"].stringify(params, {
111
+ const response = await fetch(url, {
112
+ body: querystring.stringify(params, {
128
113
  skipNull: true,
129
114
  skipEmptyString: true,
130
115
  }),
@@ -868,7 +853,7 @@ async function put(request, method, body, returnRawResultObject) {
868
853
  return request('put', method, { body }, returnRawResultObject);
869
854
  }
870
855
 
871
- var Stream$2 = stream__default["default"].Stream;
856
+ var Stream$2 = stream.Stream;
872
857
 
873
858
 
874
859
  var delayed_stream = DelayedStream;
@@ -882,7 +867,7 @@ function DelayedStream() {
882
867
  this._released = false;
883
868
  this._bufferedEvents = [];
884
869
  }
885
- util__default["default"].inherits(DelayedStream, Stream$2);
870
+ util.inherits(DelayedStream, Stream$2);
886
871
 
887
872
  DelayedStream.create = function(source, options) {
888
873
  var delayedStream = new this();
@@ -976,7 +961,7 @@ DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
976
961
  this.emit('error', new Error(message));
977
962
  };
978
963
 
979
- var Stream$1 = stream__default["default"].Stream;
964
+ var Stream$1 = stream.Stream;
980
965
 
981
966
 
982
967
  var combined_stream = CombinedStream;
@@ -993,7 +978,7 @@ function CombinedStream() {
993
978
  this._insideLoop = false;
994
979
  this._pendingNext = false;
995
980
  }
996
- util__default["default"].inherits(CombinedStream, Stream$1);
981
+ util.inherits(CombinedStream, Stream$1);
997
982
 
998
983
  CombinedStream.create = function(options) {
999
984
  var combinedStream = new this();
@@ -10850,7 +10835,7 @@ var db = {
10850
10835
 
10851
10836
  var db$1 = /*#__PURE__*/Object.freeze({
10852
10837
  __proto__: null,
10853
- 'default': db
10838
+ default: db
10854
10839
  });
10855
10840
 
10856
10841
  var require$$0 = getCjsExportFromNamespace(db$1);
@@ -10875,7 +10860,7 @@ var mimeTypes = createCommonjsModule(function (module, exports) {
10875
10860
  */
10876
10861
 
10877
10862
 
10878
- var extname = path__default["default"].extname;
10863
+ var extname = path.extname;
10879
10864
 
10880
10865
  /**
10881
10866
  * Module variables.
@@ -11429,9 +11414,9 @@ var populate = function(dst, src) {
11429
11414
  return dst;
11430
11415
  };
11431
11416
 
11432
- var parseUrl = url__default["default"].parse;
11417
+ var parseUrl = url.parse;
11433
11418
 
11434
- var Stream = stream__default["default"].Stream;
11419
+ var Stream = stream.Stream;
11435
11420
 
11436
11421
 
11437
11422
 
@@ -11440,7 +11425,7 @@ var Stream = stream__default["default"].Stream;
11440
11425
  var form_data = FormData;
11441
11426
 
11442
11427
  // make it a Stream
11443
- util__default["default"].inherits(FormData, combined_stream);
11428
+ util.inherits(FormData, combined_stream);
11444
11429
 
11445
11430
  /**
11446
11431
  * Create readable "multipart/form-data" streams.
@@ -11487,7 +11472,7 @@ FormData.prototype.append = function(field, value, options) {
11487
11472
  }
11488
11473
 
11489
11474
  // https://github.com/felixge/node-form-data/issues/38
11490
- if (util__default["default"].isArray(value)) {
11475
+ if (util.isArray(value)) {
11491
11476
  // Please convert your array into string
11492
11477
  // the way web server expects it
11493
11478
  this._error(new Error('Arrays are not supported.'));
@@ -11559,7 +11544,7 @@ FormData.prototype._lengthRetriever = function(value, callback) {
11559
11544
  // not that fast snoopy
11560
11545
  } else {
11561
11546
  // still need to fetch file size from fs
11562
- fs__default["default"].stat(value.path, function(err, stat) {
11547
+ fs.stat(value.path, function(err, stat) {
11563
11548
 
11564
11549
  var fileSize;
11565
11550
 
@@ -11649,15 +11634,15 @@ FormData.prototype._getContentDisposition = function(value, options) {
11649
11634
 
11650
11635
  if (typeof options.filepath === 'string') {
11651
11636
  // custom filepath for relative paths
11652
- filename = path__default["default"].normalize(options.filepath).replace(/\\/g, '/');
11637
+ filename = path.normalize(options.filepath).replace(/\\/g, '/');
11653
11638
  } else if (options.filename || value.name || value.path) {
11654
11639
  // custom filename take precedence
11655
11640
  // formidable and the browser add a name property
11656
11641
  // fs- and request- streams have path property
11657
- filename = path__default["default"].basename(options.filename || value.name || value.path);
11642
+ filename = path.basename(options.filename || value.name || value.path);
11658
11643
  } else if (value.readable && value.hasOwnProperty('httpVersion')) {
11659
11644
  // or try http response
11660
- filename = path__default["default"].basename(value.client._httpMessage.path || '');
11645
+ filename = path.basename(value.client._httpMessage.path || '');
11661
11646
  }
11662
11647
 
11663
11648
  if (filename) {
@@ -11876,9 +11861,9 @@ FormData.prototype.submit = function(params, cb) {
11876
11861
 
11877
11862
  // https if specified, fallback to http in any other case
11878
11863
  if (options.protocol == 'https:') {
11879
- request = https__default["default"].request(options);
11864
+ request = https.request(options);
11880
11865
  } else {
11881
- request = http__default["default"].request(options);
11866
+ request = http.request(options);
11882
11867
  }
11883
11868
 
11884
11869
  // get content length and fire away
@@ -11963,7 +11948,7 @@ const isEligibleForClientRedirect = (params) => {
11963
11948
  return false;
11964
11949
  }
11965
11950
  };
11966
- const getRedirectUrl = (params) => `${params.oauthUrl}/oauth/authorize?${querystring__default["default"].stringify(castToAuthorizationRequestParams(params), {
11951
+ const getRedirectUrl = (params) => `${params.oauthUrl}/oauth/authorize?${querystring.stringify(castToAuthorizationRequestParams(params), {
11967
11952
  skipNull: true,
11968
11953
  skipEmptyString: true,
11969
11954
  })}`;
@@ -12005,7 +11990,7 @@ async function maybeUpdateToken(oauthTokenStore, tokenFetcher, options, mustRefr
12005
11990
  return oauthTokenStore.set(await requestToken(tokenFetcher, options));
12006
11991
  }
12007
11992
  if (typeof window !== 'undefined' && options.implicit) {
12008
- const parsedLocationHash = querystring__default["default"].parse(window.location.hash);
11993
+ const parsedLocationHash = querystring.parse(window.location.hash);
12009
11994
  const accessToken = parsedLocationHash && parsedLocationHash.access_token;
12010
11995
  if (accessToken) {
12011
11996
  window.history.replaceState({}, '', window.location.href.split('#')[0]);
@@ -12039,7 +12024,7 @@ const RETRYABLE_STATUS_CODES = [
12039
12024
  401, 408, 429, 502, 503, 504,
12040
12025
  ];
12041
12026
  const TOKEN_REFRESH_STATUS_CODES = [401];
12042
- const queue = new Bottleneck__default["default"]({
12027
+ const queue = new Bottleneck({
12043
12028
  maxConcurrent: QUEUE_CONCURRENCY,
12044
12029
  minTime: QUEUE_DELAY,
12045
12030
  reservoir: QUEUE_RESERVOIR,
@@ -12108,7 +12093,7 @@ function makeApiRequest(oauthTokenStore, oauthTokenRequester, options, httpMetho
12108
12093
  const method = httpMethod.toUpperCase();
12109
12094
  const payloadQuery = payload && payload.query
12110
12095
  ? (apiMethod.includes('?') ? '&' : '?') +
12111
- querystring__default["default"].stringify(payload.query, {
12096
+ querystring.stringify(payload.query, {
12112
12097
  skipNull: true,
12113
12098
  skipEmptyString: true,
12114
12099
  })
@@ -12133,7 +12118,7 @@ function makeApiRequest(oauthTokenStore, oauthTokenRequester, options, httpMetho
12133
12118
  const requestBody = {
12134
12119
  body: hasForm ? formData : JSON.stringify(body),
12135
12120
  };
12136
- const response = await fetch__default["default"](url, Object.assign({ cache: 'no-cache', credentials: 'omit', headers,
12121
+ const response = await fetch(url, Object.assign({ cache: 'no-cache', credentials: 'omit', headers,
12137
12122
  method, mode: 'cors' }, (hasForm || body ? requestBody : {})));
12138
12123
  const result = await makeResultFromResponse(response);
12139
12124
  responseLogger.log(method, url, result instanceof Error
package/dist/lib.cjs.js CHANGED
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
3
  var querystring = require('query-string');
6
4
  var fetch = require('cross-fetch');
7
5
  var Bottleneck = require('bottleneck');
@@ -13,20 +11,7 @@ var https = require('https');
13
11
  var url = require('url');
14
12
  var fs = require('fs');
15
13
 
16
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
17
-
18
- var querystring__default = /*#__PURE__*/_interopDefaultLegacy(querystring);
19
- var fetch__default = /*#__PURE__*/_interopDefaultLegacy(fetch);
20
- var Bottleneck__default = /*#__PURE__*/_interopDefaultLegacy(Bottleneck);
21
- var util__default = /*#__PURE__*/_interopDefaultLegacy(util);
22
- var stream__default = /*#__PURE__*/_interopDefaultLegacy(stream);
23
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
24
- var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
25
- var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
26
- var url__default = /*#__PURE__*/_interopDefaultLegacy(url);
27
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
28
-
29
- const version = "5.0.3";
14
+ const version = "5.0.4";
30
15
 
31
16
  const REST_API_URL = 'https://api.allthings.me';
32
17
  const OAUTH_URL = 'https://accounts.allthings.me';
@@ -69,7 +54,7 @@ const isEligibleForClientRedirect$1 = (params) => {
69
54
  return false;
70
55
  }
71
56
  };
72
- const getRedirectUrl$1 = (params) => `${params.oauthUrl}/oauth/authorize?${querystring__default["default"].stringify(castToAuthorizationRequestParams$1(params), {
57
+ const getRedirectUrl$1 = (params) => `${params.oauthUrl}/oauth/authorize?${querystring.stringify(castToAuthorizationRequestParams$1(params), {
73
58
  skipNull: true,
74
59
  skipEmptyString: true,
75
60
  })}`;
@@ -122,8 +107,8 @@ function makeLogger(name) {
122
107
  const logger = makeLogger('OAuth Token Request');
123
108
  const makeFetchTokenRequester = (url) => async (params) => {
124
109
  try {
125
- const response = await fetch__default["default"](url, {
126
- body: querystring__default["default"].stringify(params, {
110
+ const response = await fetch(url, {
111
+ body: querystring.stringify(params, {
127
112
  skipNull: true,
128
113
  skipEmptyString: true,
129
114
  }),
@@ -867,7 +852,7 @@ async function put(request, method, body, returnRawResultObject) {
867
852
  return request('put', method, { body }, returnRawResultObject);
868
853
  }
869
854
 
870
- var Stream$2 = stream__default["default"].Stream;
855
+ var Stream$2 = stream.Stream;
871
856
 
872
857
 
873
858
  var delayed_stream = DelayedStream;
@@ -881,7 +866,7 @@ function DelayedStream() {
881
866
  this._released = false;
882
867
  this._bufferedEvents = [];
883
868
  }
884
- util__default["default"].inherits(DelayedStream, Stream$2);
869
+ util.inherits(DelayedStream, Stream$2);
885
870
 
886
871
  DelayedStream.create = function(source, options) {
887
872
  var delayedStream = new this();
@@ -975,7 +960,7 @@ DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
975
960
  this.emit('error', new Error(message));
976
961
  };
977
962
 
978
- var Stream$1 = stream__default["default"].Stream;
963
+ var Stream$1 = stream.Stream;
979
964
 
980
965
 
981
966
  var combined_stream = CombinedStream;
@@ -992,7 +977,7 @@ function CombinedStream() {
992
977
  this._insideLoop = false;
993
978
  this._pendingNext = false;
994
979
  }
995
- util__default["default"].inherits(CombinedStream, Stream$1);
980
+ util.inherits(CombinedStream, Stream$1);
996
981
 
997
982
  CombinedStream.create = function(options) {
998
983
  var combinedStream = new this();
@@ -10849,7 +10834,7 @@ var db = {
10849
10834
 
10850
10835
  var db$1 = /*#__PURE__*/Object.freeze({
10851
10836
  __proto__: null,
10852
- 'default': db
10837
+ default: db
10853
10838
  });
10854
10839
 
10855
10840
  var require$$0 = getCjsExportFromNamespace(db$1);
@@ -10874,7 +10859,7 @@ var mimeTypes = createCommonjsModule(function (module, exports) {
10874
10859
  */
10875
10860
 
10876
10861
 
10877
- var extname = path__default["default"].extname;
10862
+ var extname = path.extname;
10878
10863
 
10879
10864
  /**
10880
10865
  * Module variables.
@@ -11428,9 +11413,9 @@ var populate = function(dst, src) {
11428
11413
  return dst;
11429
11414
  };
11430
11415
 
11431
- var parseUrl = url__default["default"].parse;
11416
+ var parseUrl = url.parse;
11432
11417
 
11433
- var Stream = stream__default["default"].Stream;
11418
+ var Stream = stream.Stream;
11434
11419
 
11435
11420
 
11436
11421
 
@@ -11439,7 +11424,7 @@ var Stream = stream__default["default"].Stream;
11439
11424
  var form_data = FormData;
11440
11425
 
11441
11426
  // make it a Stream
11442
- util__default["default"].inherits(FormData, combined_stream);
11427
+ util.inherits(FormData, combined_stream);
11443
11428
 
11444
11429
  /**
11445
11430
  * Create readable "multipart/form-data" streams.
@@ -11486,7 +11471,7 @@ FormData.prototype.append = function(field, value, options) {
11486
11471
  }
11487
11472
 
11488
11473
  // https://github.com/felixge/node-form-data/issues/38
11489
- if (util__default["default"].isArray(value)) {
11474
+ if (util.isArray(value)) {
11490
11475
  // Please convert your array into string
11491
11476
  // the way web server expects it
11492
11477
  this._error(new Error('Arrays are not supported.'));
@@ -11558,7 +11543,7 @@ FormData.prototype._lengthRetriever = function(value, callback) {
11558
11543
  // not that fast snoopy
11559
11544
  } else {
11560
11545
  // still need to fetch file size from fs
11561
- fs__default["default"].stat(value.path, function(err, stat) {
11546
+ fs.stat(value.path, function(err, stat) {
11562
11547
 
11563
11548
  var fileSize;
11564
11549
 
@@ -11648,15 +11633,15 @@ FormData.prototype._getContentDisposition = function(value, options) {
11648
11633
 
11649
11634
  if (typeof options.filepath === 'string') {
11650
11635
  // custom filepath for relative paths
11651
- filename = path__default["default"].normalize(options.filepath).replace(/\\/g, '/');
11636
+ filename = path.normalize(options.filepath).replace(/\\/g, '/');
11652
11637
  } else if (options.filename || value.name || value.path) {
11653
11638
  // custom filename take precedence
11654
11639
  // formidable and the browser add a name property
11655
11640
  // fs- and request- streams have path property
11656
- filename = path__default["default"].basename(options.filename || value.name || value.path);
11641
+ filename = path.basename(options.filename || value.name || value.path);
11657
11642
  } else if (value.readable && value.hasOwnProperty('httpVersion')) {
11658
11643
  // or try http response
11659
- filename = path__default["default"].basename(value.client._httpMessage.path || '');
11644
+ filename = path.basename(value.client._httpMessage.path || '');
11660
11645
  }
11661
11646
 
11662
11647
  if (filename) {
@@ -11875,9 +11860,9 @@ FormData.prototype.submit = function(params, cb) {
11875
11860
 
11876
11861
  // https if specified, fallback to http in any other case
11877
11862
  if (options.protocol == 'https:') {
11878
- request = https__default["default"].request(options);
11863
+ request = https.request(options);
11879
11864
  } else {
11880
- request = http__default["default"].request(options);
11865
+ request = http.request(options);
11881
11866
  }
11882
11867
 
11883
11868
  // get content length and fire away
@@ -11962,7 +11947,7 @@ const isEligibleForClientRedirect = (params) => {
11962
11947
  return false;
11963
11948
  }
11964
11949
  };
11965
- const getRedirectUrl = (params) => `${params.oauthUrl}/oauth/authorize?${querystring__default["default"].stringify(castToAuthorizationRequestParams(params), {
11950
+ const getRedirectUrl = (params) => `${params.oauthUrl}/oauth/authorize?${querystring.stringify(castToAuthorizationRequestParams(params), {
11966
11951
  skipNull: true,
11967
11952
  skipEmptyString: true,
11968
11953
  })}`;
@@ -12004,7 +11989,7 @@ async function maybeUpdateToken(oauthTokenStore, tokenFetcher, options, mustRefr
12004
11989
  return oauthTokenStore.set(await requestToken(tokenFetcher, options));
12005
11990
  }
12006
11991
  if (typeof window !== 'undefined' && options.implicit) {
12007
- const parsedLocationHash = querystring__default["default"].parse(window.location.hash);
11992
+ const parsedLocationHash = querystring.parse(window.location.hash);
12008
11993
  const accessToken = parsedLocationHash && parsedLocationHash.access_token;
12009
11994
  if (accessToken) {
12010
11995
  window.history.replaceState({}, '', window.location.href.split('#')[0]);
@@ -12038,7 +12023,7 @@ const RETRYABLE_STATUS_CODES = [
12038
12023
  401, 408, 429, 502, 503, 504,
12039
12024
  ];
12040
12025
  const TOKEN_REFRESH_STATUS_CODES = [401];
12041
- const queue = new Bottleneck__default["default"]({
12026
+ const queue = new Bottleneck({
12042
12027
  maxConcurrent: QUEUE_CONCURRENCY,
12043
12028
  minTime: QUEUE_DELAY,
12044
12029
  reservoir: QUEUE_RESERVOIR,
@@ -12107,7 +12092,7 @@ function makeApiRequest(oauthTokenStore, oauthTokenRequester, options, httpMetho
12107
12092
  const method = httpMethod.toUpperCase();
12108
12093
  const payloadQuery = payload && payload.query
12109
12094
  ? (apiMethod.includes('?') ? '&' : '?') +
12110
- querystring__default["default"].stringify(payload.query, {
12095
+ querystring.stringify(payload.query, {
12111
12096
  skipNull: true,
12112
12097
  skipEmptyString: true,
12113
12098
  })
@@ -12132,7 +12117,7 @@ function makeApiRequest(oauthTokenStore, oauthTokenRequester, options, httpMetho
12132
12117
  const requestBody = {
12133
12118
  body: hasForm ? formData : JSON.stringify(body),
12134
12119
  };
12135
- const response = await fetch__default["default"](url, Object.assign({ cache: 'no-cache', credentials: 'omit', headers,
12120
+ const response = await fetch(url, Object.assign({ cache: 'no-cache', credentials: 'omit', headers,
12136
12121
  method, mode: 'cors' }, (hasForm || body ? requestBody : {})));
12137
12122
  const result = await makeResultFromResponse(response);
12138
12123
  responseLogger.log(method, url, result instanceof Error
package/dist/lib.esm.js CHANGED
@@ -9,7 +9,7 @@ import https from 'https';
9
9
  import url from 'url';
10
10
  import fs from 'fs';
11
11
 
12
- const version = "5.0.3";
12
+ const version = "5.0.4";
13
13
 
14
14
  const REST_API_URL = 'https://api.allthings.me';
15
15
  const OAUTH_URL = 'https://accounts.allthings.me';
@@ -10832,7 +10832,7 @@ var db = {
10832
10832
 
10833
10833
  var db$1 = /*#__PURE__*/Object.freeze({
10834
10834
  __proto__: null,
10835
- 'default': db
10835
+ default: db
10836
10836
  });
10837
10837
 
10838
10838
  var require$$0 = getCjsExportFromNamespace(db$1);
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).allthings={})}(this,(function(exports){"use strict";const version$3="5.0.3",REST_API_URL="https://api.allthings.me",OAUTH_URL="https://accounts.allthings.me",QUEUE_CONCURRENCY=void 0,QUEUE_DELAY=0,QUEUE_RESERVOIR=30,QUEUE_RESERVOIR_REFILL_INTERVAL=166,REQUEST_BACK_OFF_INTERVAL=200,REQUEST_MAX_RETRIES=50,DEFAULT_API_WRAPPER_OPTIONS={apiUrl:[].ALLTHINGS_REST_API_URL||REST_API_URL,clientId:[].ALLTHINGS_OAUTH_CLIENT_ID,clientSecret:[].ALLTHINGS_OAUTH_CLIENT_SECRET,oauthUrl:[].ALLTHINGS_OAUTH_URL||OAUTH_URL,password:[].ALLTHINGS_OAUTH_PASSWORD,requestBackOffInterval:REQUEST_BACK_OFF_INTERVAL,requestMaxRetries:REQUEST_MAX_RETRIES,scope:"user:profile",username:[].ALLTHINGS_OAUTH_USERNAME},USER_AGENT=`Allthings Node SDK REST Client/${version$3}`;var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function unwrapExports(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function createCommonjsModule(e,t){return e(t={exports:{}},t.exports),t.exports}function getCjsExportFromNamespace(e){return e&&e.default||e}var strictUriEncode=e=>encodeURIComponent(e).replace(/[!'()*]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),token="%[a-f0-9]{2}",singleMatcher=new RegExp("("+token+")|([^%]+?)","gi"),multiMatcher=new RegExp("("+token+")+","gi");function decodeComponents(e,t){try{return[decodeURIComponent(e.join(""))]}catch(e){}if(1===e.length)return e;t=t||1;var n=e.slice(0,t),r=e.slice(t);return Array.prototype.concat.call([],decodeComponents(n),decodeComponents(r))}function decode(e){try{return decodeURIComponent(e)}catch(r){for(var t=e.match(singleMatcher)||[],n=1;n<t.length;n++)t=(e=decodeComponents(t,n).join("")).match(singleMatcher)||[];return e}}function customDecodeURIComponent(e){for(var t={"%FE%FF":"��","%FF%FE":"��"},n=multiMatcher.exec(e);n;){try{t[n[0]]=decodeURIComponent(n[0])}catch(e){var r=decode(n[0]);r!==n[0]&&(t[n[0]]=r)}n=multiMatcher.exec(e)}t["%C2"]="�";for(var i=Object.keys(t),s=0;s<i.length;s++){var o=i[s];e=e.replace(new RegExp(o,"g"),t[o])}return e}var decodeUriComponent=function(e){if("string"!=typeof e)throw new TypeError("Expected `encodedURI` to be of type `string`, got `"+typeof e+"`");try{return e=e.replace(/\+/g," "),decodeURIComponent(e)}catch(t){return customDecodeURIComponent(e)}},splitOnFirst=(e,t)=>{if("string"!=typeof e||"string"!=typeof t)throw new TypeError("Expected the arguments to be of type `string`");if(""===t)return[e];const n=e.indexOf(t);return-1===n?[e]:[e.slice(0,n),e.slice(n+t.length)]},filterObj=function(e,t){for(var n={},r=Object.keys(e),i=Array.isArray(t),s=0;s<r.length;s++){var o=r[s],a=e[o];(i?-1!==t.indexOf(o):t(o,a,e))&&(n[o]=a)}return n},queryString=createCommonjsModule((function(e,t){const n=Symbol("encodeFragmentIdentifier");function r(e){if("string"!=typeof e||1!==e.length)throw new TypeError("arrayFormatSeparator must be single character string")}function i(e,t){return t.encode?t.strict?strictUriEncode(e):encodeURIComponent(e):e}function s(e,t){return t.decode?decodeUriComponent(e):e}function o(e){return Array.isArray(e)?e.sort():"object"==typeof e?o(Object.keys(e)).sort(((e,t)=>Number(e)-Number(t))).map((t=>e[t])):e}function a(e){const t=e.indexOf("#");return-1!==t&&(e=e.slice(0,t)),e}function c(e){const t=(e=a(e)).indexOf("?");return-1===t?"":e.slice(t+1)}function u(e,t){return t.parseNumbers&&!Number.isNaN(Number(e))&&"string"==typeof e&&""!==e.trim()?e=Number(e):!t.parseBooleans||null===e||"true"!==e.toLowerCase()&&"false"!==e.toLowerCase()||(e="true"===e.toLowerCase()),e}function l(e,t){r((t=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},t)).arrayFormatSeparator);const n=function(e){let t;switch(e.arrayFormat){case"index":return(e,n,r)=>{t=/\[(\d*)\]$/.exec(e),e=e.replace(/\[\d*\]$/,""),t?(void 0===r[e]&&(r[e]={}),r[e][t[1]]=n):r[e]=n};case"bracket":return(e,n,r)=>{t=/(\[\])$/.exec(e),e=e.replace(/\[\]$/,""),t?void 0!==r[e]?r[e]=[].concat(r[e],n):r[e]=[n]:r[e]=n};case"colon-list-separator":return(e,n,r)=>{t=/(:list)$/.exec(e),e=e.replace(/:list$/,""),t?void 0!==r[e]?r[e]=[].concat(r[e],n):r[e]=[n]:r[e]=n};case"comma":case"separator":return(t,n,r)=>{const i="string"==typeof n&&n.includes(e.arrayFormatSeparator),o="string"==typeof n&&!i&&s(n,e).includes(e.arrayFormatSeparator);n=o?s(n,e):n;const a=i||o?n.split(e.arrayFormatSeparator).map((t=>s(t,e))):null===n?n:s(n,e);r[t]=a};case"bracket-separator":return(t,n,r)=>{const i=/(\[\])$/.test(t);if(t=t.replace(/\[\]$/,""),!i)return void(r[t]=n?s(n,e):n);const o=null===n?[]:n.split(e.arrayFormatSeparator).map((t=>s(t,e)));void 0!==r[t]?r[t]=[].concat(r[t],o):r[t]=o};default:return(e,t,n)=>{void 0!==n[e]?n[e]=[].concat(n[e],t):n[e]=t}}}(t),i=Object.create(null);if("string"!=typeof e)return i;if(!(e=e.trim().replace(/^[?#&]/,"")))return i;for(const r of e.split("&")){if(""===r)continue;let[e,o]=splitOnFirst(t.decode?r.replace(/\+/g," "):r,"=");o=void 0===o?null:["comma","separator","bracket-separator"].includes(t.arrayFormat)?o:s(o,t),n(s(e,t),o,i)}for(const e of Object.keys(i)){const n=i[e];if("object"==typeof n&&null!==n)for(const e of Object.keys(n))n[e]=u(n[e],t);else i[e]=u(n,t)}return!1===t.sort?i:(!0===t.sort?Object.keys(i).sort():Object.keys(i).sort(t.sort)).reduce(((e,t)=>{const n=i[t];return Boolean(n)&&"object"==typeof n&&!Array.isArray(n)?e[t]=o(n):e[t]=n,e}),Object.create(null))}t.extract=c,t.parse=l,t.stringify=(e,t)=>{if(!e)return"";r((t=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},t)).arrayFormatSeparator);const n=n=>t.skipNull&&null==e[n]||t.skipEmptyString&&""===e[n],s=function(e){switch(e.arrayFormat){case"index":return t=>(n,r)=>{const s=n.length;return void 0===r||e.skipNull&&null===r||e.skipEmptyString&&""===r?n:null===r?[...n,[i(t,e),"[",s,"]"].join("")]:[...n,[i(t,e),"[",i(s,e),"]=",i(r,e)].join("")]};case"bracket":return t=>(n,r)=>void 0===r||e.skipNull&&null===r||e.skipEmptyString&&""===r?n:null===r?[...n,[i(t,e),"[]"].join("")]:[...n,[i(t,e),"[]=",i(r,e)].join("")];case"colon-list-separator":return t=>(n,r)=>void 0===r||e.skipNull&&null===r||e.skipEmptyString&&""===r?n:null===r?[...n,[i(t,e),":list="].join("")]:[...n,[i(t,e),":list=",i(r,e)].join("")];case"comma":case"separator":case"bracket-separator":{const t="bracket-separator"===e.arrayFormat?"[]=":"=";return n=>(r,s)=>void 0===s||e.skipNull&&null===s||e.skipEmptyString&&""===s?r:(s=null===s?"":s,0===r.length?[[i(n,e),t,i(s,e)].join("")]:[[r,i(s,e)].join(e.arrayFormatSeparator)])}default:return t=>(n,r)=>void 0===r||e.skipNull&&null===r||e.skipEmptyString&&""===r?n:null===r?[...n,i(t,e)]:[...n,[i(t,e),"=",i(r,e)].join("")]}}(t),o={};for(const t of Object.keys(e))n(t)||(o[t]=e[t]);const a=Object.keys(o);return!1!==t.sort&&a.sort(t.sort),a.map((n=>{const r=e[n];return void 0===r?"":null===r?i(n,t):Array.isArray(r)?0===r.length&&"bracket-separator"===t.arrayFormat?i(n,t)+"[]":r.reduce(s(n),[]).join("&"):i(n,t)+"="+i(r,t)})).filter((e=>e.length>0)).join("&")},t.parseUrl=(e,t)=>{t=Object.assign({decode:!0},t);const[n,r]=splitOnFirst(e,"#");return Object.assign({url:n.split("?")[0]||"",query:l(c(e),t)},t&&t.parseFragmentIdentifier&&r?{fragmentIdentifier:s(r,t)}:{})},t.stringifyUrl=(e,r)=>{r=Object.assign({encode:!0,strict:!0,[n]:!0},r);const s=a(e.url).split("?")[0]||"",o=t.extract(e.url),c=t.parse(o,{sort:!1}),u=Object.assign(c,e.query);let l=t.stringify(u,r);l&&(l=`?${l}`);let d=function(e){let t="";const n=e.indexOf("#");return-1!==n&&(t=e.slice(n)),t}(e.url);return e.fragmentIdentifier&&(d=`#${r[n]?i(e.fragmentIdentifier,r):e.fragmentIdentifier}`),`${s}${l}${d}`},t.pick=(e,r,i)=>{i=Object.assign({parseFragmentIdentifier:!0,[n]:!1},i);const{url:s,query:o,fragmentIdentifier:a}=t.parseUrl(e,i);return t.stringifyUrl({url:s,query:filterObj(o,r),fragmentIdentifier:a},i)},t.exclude=(e,n,r)=>{const i=Array.isArray(n)?e=>!n.includes(e):(e,t)=>!n(e,t);return t.pick(e,i,r)}}));queryString.extract,queryString.parse,queryString.stringify,queryString.parseUrl,queryString.stringifyUrl,queryString.pick,queryString.exclude;const RESPONSE_TYPE$1="code",GRANT_TYPE$3="authorization_code",castToAuthorizationRequestParams$1=e=>{const{redirectUri:t,clientId:n,scope:r,state:i}=e;if(!n)throw new Error('Missing required "clientId" parameter to perform authorization code grant redirect');if(!t)throw new Error('Missing required "redirectUri" parameter to perform authorization code grant redirect');return Object.assign(Object.assign({client_id:n,redirect_uri:t,response_type:RESPONSE_TYPE$1},r?{scope:r}:{}),i?{state:i}:{})},isEligibleForClientRedirect$1=e=>{try{return!!castToAuthorizationRequestParams$1(e)}catch(e){return!1}},getRedirectUrl$1=e=>`${e.oauthUrl}/oauth/authorize?${queryString.stringify(castToAuthorizationRequestParams$1(e),{skipNull:!0,skipEmptyString:!0})}`,castToTokenRequestParams$2=e=>{const{authorizationCode:t,redirectUri:n,clientId:r,clientSecret:i}=e;if(!r)throw new Error('Missing required "clientId" parameter to perform authorization code grant');if(!n)throw new Error('Missing required "redirectUri" parameter to perform authorization code grant');if(!t)throw new Error('Missing required "authorizationCode" parameter to perform authorization code grant');return Object.assign({client_id:r,code:t,grant_type:GRANT_TYPE$3,redirect_uri:n},i?{client_secret:i}:{})},isEligible$3=e=>{try{return!!castToTokenRequestParams$2(e)}catch(e){return!1}},requestToken$3=(e,t)=>e(castToTokenRequestParams$2(t));function createTokenStore(e){const t=new Map(Object.entries(e||{}));return{get:e=>t.get(e),reset:()=>t.clear(),set:e=>Object.entries(e).forEach((([e,n])=>t.set(e,n)))}}var browserPonyfill=createCommonjsModule((function(e,t){var n="undefined"!=typeof self?self:commonjsGlobal,r=function(){function e(){this.fetch=!1,this.DOMException=n.DOMException}return e.prototype=n,new e}();!function(e){!function(t){var n="URLSearchParams"in e,r="Symbol"in e&&"iterator"in Symbol,i="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),s="FormData"in e,o="ArrayBuffer"in e;if(o)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(e){return e&&a.indexOf(Object.prototype.toString.call(e))>-1};function u(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function l(e){return"string"!=typeof e&&(e=String(e)),e}function d(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return r&&(t[Symbol.iterator]=function(){return t}),t}function p(e){this.map={},e instanceof p?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function h(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function m(e){return new Promise((function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}}))}function y(e){var t=new FileReader,n=m(t);return t.readAsArrayBuffer(e),n}function _(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function f(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:i&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:s&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:n&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():o&&i&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=_(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):o&&(ArrayBuffer.prototype.isPrototypeOf(e)||c(e))?this._bodyArrayBuffer=_(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):n&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var e=h(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?h(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(y)}),this.text=function(){var e,t,n,r=h(this);if(r)return r;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,n=m(t),t.readAsText(e),n;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),n=new Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},s&&(this.formData=function(){return this.text().then(b)}),this.json=function(){return this.text().then(JSON.parse)},this}p.prototype.append=function(e,t){e=u(e),t=l(t);var n=this.map[e];this.map[e]=n?n+", "+t:t},p.prototype.delete=function(e){delete this.map[u(e)]},p.prototype.get=function(e){return e=u(e),this.has(e)?this.map[e]:null},p.prototype.has=function(e){return this.map.hasOwnProperty(u(e))},p.prototype.set=function(e,t){this.map[u(e)]=l(t)},p.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},p.prototype.keys=function(){var e=[];return this.forEach((function(t,n){e.push(n)})),d(e)},p.prototype.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),d(e)},p.prototype.entries=function(){var e=[];return this.forEach((function(t,n){e.push([n,t])})),d(e)},r&&(p.prototype[Symbol.iterator]=p.prototype.entries);var g=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function v(e,t){var n,r,i=(t=t||{}).body;if(e instanceof v){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new p(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,i||null==e._bodyInit||(i=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new p(t.headers)),this.method=(n=t.method||this.method||"GET",r=n.toUpperCase(),g.indexOf(r)>-1?r:n),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function b(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var n=e.split("="),r=n.shift().replace(/\+/g," "),i=n.join("=").replace(/\+/g," ");t.append(decodeURIComponent(r),decodeURIComponent(i))}})),t}function E(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new p(t.headers),this.url=t.url||"",this._initBody(e)}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})},f.call(v.prototype),f.call(E.prototype),E.prototype.clone=function(){return new E(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},E.error=function(){var e=new E(null,{status:0,statusText:""});return e.type="error",e};var T=[301,302,303,307,308];E.redirect=function(e,t){if(-1===T.indexOf(t))throw new RangeError("Invalid status code");return new E(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function k(e,n){return new Promise((function(r,s){var o=new v(e,n);if(o.signal&&o.signal.aborted)return s(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function c(){a.abort()}a.onload=function(){var e,t,n={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new p,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var n=e.split(":"),r=n.shift().trim();if(r){var i=n.join(":").trim();t.append(r,i)}})),t)};n.url="responseURL"in a?a.responseURL:n.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;r(new E(i,n))},a.onerror=function(){s(new TypeError("Network request failed"))},a.ontimeout=function(){s(new TypeError("Network request failed"))},a.onabort=function(){s(new t.DOMException("Aborted","AbortError"))},a.open(o.method,o.url,!0),"include"===o.credentials?a.withCredentials=!0:"omit"===o.credentials&&(a.withCredentials=!1),"responseType"in a&&i&&(a.responseType="blob"),o.headers.forEach((function(e,t){a.setRequestHeader(t,e)})),o.signal&&(o.signal.addEventListener("abort",c),a.onreadystatechange=function(){4===a.readyState&&o.signal.removeEventListener("abort",c)}),a.send(void 0===o._bodyInit?null:o._bodyInit)}))}k.polyfill=!0,e.fetch||(e.fetch=k,e.Headers=p,e.Request=v,e.Response=E),t.Headers=p,t.Request=v,t.Response=E,t.fetch=k,Object.defineProperty(t,"__esModule",{value:!0})}({})}(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=r;(t=i.fetch).default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t})),fetch=unwrapExports(browserPonyfill);browserPonyfill.fetch,browserPonyfill.Headers,browserPonyfill.Request,browserPonyfill.Response;const SUBSCRIPTIONS=[].DEBUG&&[].DEBUG.split(",").map((e=>e.trim()))||[];function makeLogger(e){return["log","info","warn","error"].reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:function(...t){return(SUBSCRIPTIONS.includes("*")||SUBSCRIPTIONS.includes(e)||SUBSCRIPTIONS.includes(e.toLocaleLowerCase()))&&console[n](`${e}:`,...t),!0}})),{})}const logger=makeLogger("OAuth Token Request"),makeFetchTokenRequester=e=>async t=>{try{const n=await fetch(e,{body:queryString.stringify(t,{skipNull:!0,skipEmptyString:!0}),cache:"no-cache",credentials:"omit",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":USER_AGENT},method:"POST",mode:"cors"});if(200!==n.status)throw n;const{access_token:r,refresh_token:i,expires_in:s}=await n.json();return{accessToken:r,expiresIn:s,refreshToken:i}}catch(e){if(!e.status)throw e;const t=`HTTP ${e.status} — ${e.statusText}`;throw logger.error(t,e.response),new Error(`HTTP ${e.status} — ${e.statusText}. Could not get token.`)}},GRANT_TYPE$2="refresh_token",castToTokenRequestParams$1=e=>{const{clientId:t,clientSecret:n,refreshToken:r,scope:i}=e;if(!t)throw new Error('Missing required "clientId" parameter to perform refresh token grant');if(!r)throw new Error('Missing required "refreshToken" parameter to perform refresh token grant');return Object.assign(Object.assign({client_id:t,grant_type:GRANT_TYPE$2,refresh_token:r},n?{client_secret:n}:{}),i?{scope:i}:{})},isEligible$2=e=>{try{return!!castToTokenRequestParams$1(e)}catch(e){return!1}},requestToken$2=(e,t)=>e(castToTokenRequestParams$1(t));async function requestAndSaveToStore(e,t){const n=await e();return t.set(n),n}const partial=(e,...t)=>(...n)=>e(...t,...n);async function until(e,t,n,r=0){const i=await t(n,r);return await e(i,r)?i:until(e,t,i,r+1)}function fnClearInterval(e){return clearInterval(e),!0}function pseudoRandomString(e=16){let t="";for(;t.length<e;)t+=Math.random().toString(36).substr(2);return t.substr(0,e)}async function del(e,t,n,r){return e("delete",t,{body:n},r)}async function get(e,t,n,r){return e("get",t,{query:n},r)}var __rest$4=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n},EnumGender,EnumUserType,EnumCommunicationPreferenceChannel,EnumUserPermissionRole,EnumUserPermissionObjectType;!function(e){e.female="female",e.male="male"}(EnumGender||(EnumGender={})),function(e){e.allthingsUser="allthings_user",e.allthingsContent="allthings_content",e.customer="customer",e.demoContent="demo_content",e.demoPublic="demo_public",e.partner="partner"}(EnumUserType||(EnumUserType={})),exports.EnumCommunicationPreferenceChannel=void 0,EnumCommunicationPreferenceChannel=exports.EnumCommunicationPreferenceChannel||(exports.EnumCommunicationPreferenceChannel={}),EnumCommunicationPreferenceChannel.push="push",EnumCommunicationPreferenceChannel.email="email",exports.EnumUserPermissionRole=void 0,EnumUserPermissionRole=exports.EnumUserPermissionRole||(exports.EnumUserPermissionRole={}),EnumUserPermissionRole.appAdmin="app-admin",EnumUserPermissionRole.appOwner="app-owner",EnumUserPermissionRole.articlesAgent="articles-agent",EnumUserPermissionRole.articlesViewOnly="articles-view-only",EnumUserPermissionRole.bookableAssetAgent="bookable-asset-agent",EnumUserPermissionRole.bookingAgent="booking-agent",EnumUserPermissionRole.cockpitManager="cockpit-manager",EnumUserPermissionRole.dataConnectorAdmin="data-connector-admin",EnumUserPermissionRole.documentAdmin="doc-admin",EnumUserPermissionRole.externalAgent="external-agent",EnumUserPermissionRole.globalOrgAdmin="global-org-admin",EnumUserPermissionRole.globalUserAdmin="global-user-admin",EnumUserPermissionRole.orgAdmin="org-admin",EnumUserPermissionRole.orgTeamManager="org-team-manager",EnumUserPermissionRole.pinboardAgent="pinboard-agent",EnumUserPermissionRole.platformOwner="platform-owner",EnumUserPermissionRole.qa="qa",EnumUserPermissionRole.serviceCenterAgent="service-center-agent",EnumUserPermissionRole.serviceCenterManager="service-center-manager",EnumUserPermissionRole.setup="setup",EnumUserPermissionRole.tenantManager="tenant-manager",exports.EnumUserPermissionObjectType=void 0,EnumUserPermissionObjectType=exports.EnumUserPermissionObjectType||(exports.EnumUserPermissionObjectType={}),EnumUserPermissionObjectType.app="App",EnumUserPermissionObjectType.group="Group",EnumUserPermissionObjectType.property="Property",EnumUserPermissionObjectType.unit="Unit";const remapUserResult=e=>{const{tenantIDs:t}=e,n=__rest$4(e,["tenantIDs"]);return Object.assign(Object.assign({},n),{tenantIds:t})},remapEmbeddedUser=e=>e.users?e.users.map(remapUserResult):[];async function userCreate(e,t,n,r){return e.post("/v1/users",Object.assign(Object.assign({},r),{creationContext:t,username:n}))}async function getUsers(e,t=1,n=-1,r={}){const{_embedded:{items:i},total:s}=await e.get("/v1/users",{filter:JSON.stringify(r),limit:n,page:t});return{_embedded:{items:i.map(remapUserResult)},total:s}}async function getCurrentUser(e){return remapUserResult(await e.get("/v1/me"))}async function userGetById(e,t){return remapUserResult(await e.get(`/v1/users/${t}`))}async function userUpdateById(e,t,n){const{tenantIds:r}=n,i=__rest$4(n,["tenantIds"]);return remapUserResult(await e.patch(`/v1/users/${t}`,Object.assign(Object.assign({},i),{tenantIDs:r})))}async function userCreatePermission(e,t,n){const{objectId:r}=n,i=__rest$4(n,["objectId"]),s=await e.post(`/v1/users/${t}/permissions`,Object.assign(Object.assign({},i),{objectID:r})),{objectID:o}=s,a=__rest$4(s,["objectID"]);return Object.assign(Object.assign({},a),{objectId:o})}async function userCreatePermissionBatch(e,t,n){const{objectId:r,objectType:i,roles:s,startDate:o,endDate:a}=n,c={batch:s.map((e=>({endDate:a&&a.toISOString(),objectID:r,objectType:i,restrictions:[],role:e,startDate:o&&o.toISOString()})))};return!await e.post(`/v1/users/${t}/permissions`,c)}async function userGetPermissions(e,t){const{_embedded:{items:n}}=await e.get(`/v1/users/${t}/roles?limit=-1`);return n.map((e=>{var{objectID:t}=e,n=__rest$4(e,["objectID"]);return Object.assign(Object.assign({},n),{objectId:t})}))}async function userDeletePermission(e,t){return!await e.delete(`/v1/permissions/${t}`)}async function userGetUtilisationPeriods(e,t){const{_embedded:{items:n}}=await e.get(`/v1/users/${t}/utilisation-periods`);return n}async function userCheckInToUtilisationPeriod(e,t,n){const{email:r}=await e.userGetById(t);return e.utilisationPeriodCheckInUser(n,{email:r})}async function userGetByEmail(e,t,n=1,r=1e3){return e.getUsers(n,r,{email:t})}async function userChangePassword(e,t,n,r){return!await e.put(`/v1/users/${t}/password`,{currentPassword:n,plainPassword:r})}async function agentCreate(e,t,n,r,i,s,o){const a=await e.userCreate(t,r,Object.assign(Object.assign({},i),{type:EnumUserType.customer})),c=await e.post(`/v1/property-managers/${n}/users`,Object.assign({userID:a.id},o&&{externalAgentCompany:o}));return!((void 0===s||s)&&await e.post(`/v1/users/${a.id}/invitations`))&&Object.assign(Object.assign({},a),c)}async function agentCreatePermissions(e,t,n,r,i,s,o){return e.userCreatePermissionBatch(t,{endDate:o,objectId:n,objectType:r,restrictions:[],roles:i,startDate:s})}async function appCreate(e,t,n){return e.post(`/v1/users/${t}/apps`,Object.assign(Object.assign({availableLocales:{0:"de_DE"}},n),{siteUrl:n.siteUrl.replace("_","")}))}async function appGetById(e,t){return e.get(`/v1/apps/${t}`)}async function activeUnitsGetByAppId(e,t){return e.get(`/v1/apps/${t}/active-units`)}async function bookingGetById(e,t){return e.get(`/v1/bookings/${t}`)}async function bookingUpdateById(e,t,n){return e.patch(`/v1/bookings/${t}`,n)}async function bucketGet(e,t){return e.get(`/v1/buckets/${t}`)}async function bucketCreate(e,t){return e.post("/v1/buckets",{channels:t.channels,name:t.name})}async function bucketAddFile(e,t,n){return""===await e.post(`/v1/buckets/${t}/files`,{id:n})}async function bucketRemoveFile(e,t,n){return""===await e.delete(`/v1/buckets/${t}/files/${n}`)}async function bucketRemoveFilesInPath(e,t,n){return""===await e.delete(`/v1/buckets/${t}/files`,{folder:n.path})}const createManyFiles=async(e,t)=>await Promise.all(e.map((async e=>{try{return await t.fileCreate({file:e.content,name:e.filename})}catch(e){return e}})));async function createManyFilesSorted(e,t){const n=await createManyFiles(e,t);return{error:n.filter((e=>e instanceof Error)),success:n.filter((e=>!(e instanceof Error))).map((e=>e.id))}}async function conversationGetById(e,t){return e.get(`/v1/conversations/${t}`)}async function conversationCreateMessage(e,t,n){const r=`/v1/conversations/${t}/messages`,i=n.attachments&&n.attachments.length?{content:{description:n.body,files:(await createManyFilesSorted(n.attachments,e)).success},createdBy:n.createdBy,inputChannel:n.inputChannel,internal:!1,type:"file"}:{content:{content:n.body},createdBy:n.createdBy,inputChannel:n.inputChannel,type:"text"};return e.post(r,i)}async function fileCreate(e,t){return e.post("/v1/files",{formData:{file:[t.file,t.name],path:t.path||""}})}async function fileDelete(e,t){return""===await e.delete(`/v1/files/${t}`)}var __rest$3=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n};async function groupCreate(e,t,n){const{propertyManagerId:r}=n,i=__rest$3(n,["propertyManagerId"]);return e.post(`/v1/properties/${t}/groups`,Object.assign(Object.assign({},i),{propertyManagerID:r}))}async function groupGetById(e,t){const n=await e.get(`/v1/groups/${t}`),{propertyManagerID:r}=n,i=__rest$3(n,["propertyManagerID"]);return Object.assign(Object.assign({},i),{propertyManagerId:r})}async function groupUpdateById(e,t,n){return e.patch(`/v1/groups/${t}`,n)}async function getGroups(e,t=1,n=-1,r={}){const{_embedded:{items:i},total:s}=await e.get("/v1/groups",{filter:JSON.stringify(r),limit:n,page:t});return{_embedded:{items:i},total:s}}async function lookupIds(e,t,n){return e.post(`/v1/id-lookup/${t}/${n.resource}`,Object.assign(Object.assign({externalIds:"string"==typeof n.externalIds?[n.externalIds]:n.externalIds},n.parentId?{parentId:n.parentId}:{}),n.userType?{userType:n.userType}:{}))}function stringToDate(e){return new Date(Date.parse(e))}function dateToString(e){return e.toISOString()}var __rest$2=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n},EnumNotificationCategory,EnumNotificationType,EnumNotificationSettingsValue;function remapNotificationResult(e){var{createdAt:t,objectID:n,referencedObjectID:r}=e,i=__rest$2(e,["createdAt","objectID","referencedObjectID"]);return Object.assign({createdAt:stringToDate(t),objectId:n,referencedObjectId:r},i)}async function notificationsGetByUser(e,t,n=1,r=-1){const{_embedded:{items:i},total:s,metaData:o}=await e.get(`/v1/users/${t}/notifications?page=${n}&limit=${r}`);return{_embedded:{items:i.map(remapNotificationResult)},metaData:o,total:s}}async function notificationsUpdateReadByUser(e,t,n=new Date){return e.patch(`/v1/users/${t}/notifications`,{lastReadAt:dateToString(n)})}async function notificationUpdateRead(e,t){return remapNotificationResult(await e.patch(`/v1/notifications/${t}`,{read:!0}))}function remapKeys(e,t){return Object.entries(e).reduce(((e,n)=>Object.assign(Object.assign({},e),{[t(n[0])]:n[1]})),{})}function camelCaseToDash(e){return e.replace(/([A-Z])/g,(e=>`-${e[0].toLowerCase()}`))}function dashCaseToCamel(e){return e.replace(/-([a-z])/g,(e=>e[1].toUpperCase()))}async function notificationSettingsUpdateByUser(e,t,n){const r=await e.patch(`/v1/users/${t}/notification-settings`,{notificationSettings:remapKeys(n,camelCaseToDash)});return remapKeys(r,dashCaseToCamel)}async function notificationSettingsResetByUser(e,t){return remapKeys(await e.delete(`/v1/users/${t}/notification-settings`),dashCaseToCamel)}async function propertyCreate(e,t,n){return e.post(`/v1/apps/${t}/properties`,n)}async function propertyGetById(e,t){return e.get(`/v1/properties/${t}`)}async function propertyUpdateById(e,t,n){return e.patch(`/v1/properties/${t}`,n)}async function getProperties(e,t=1,n=-1,r={}){const{_embedded:{items:i},total:s}=await e.get("/v1/properties",{filter:JSON.stringify(r),limit:n,page:t});return{_embedded:{items:i},total:s}}!function(e){e.events="events",e.hintsAndTips="hints-and-tips",e.lostAndFound="lost-and-found",e.localDeals="local-deals",e.localEvents="local-events",e.miscellaneous="miscellaneous",e.deals="deals",e.messages="messages",e.adminMessages="admin-messages",e.newThingsToGive="new-things-to-give",e.newThingsForSale="new-things-for-sale",e.surveys="surveys",e.supportOffer="support-offer",e.supportRequest="support-request",e.sustainability="sustainability",e.localServices="local-services",e.services="services",e.ticketDigestEmail="ticket-digest-email",e.appDigestEmail="app-digest-email",e.newFile="new-file"}(EnumNotificationCategory||(EnumNotificationCategory={})),function(e){e.clipboardThing="clipboard-thing",e.comment="comment",e.communityArticle="community-article",e.newFile="new-file",e.ticketComment="ticket-comment",e.welcomeNotification="welcome-notification"}(EnumNotificationType||(EnumNotificationType={})),function(e){e.never="never",e.immediately="immediately",e.daily="daily",e.weekly="weekly",e.biweekly="biweekly",e.monthly="monthly"}(EnumNotificationSettingsValue||(EnumNotificationSettingsValue={}));var __rest$1=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n};const remapRegistationCodeResult=e=>{const{tenantID:t}=e,n=__rest$1(e,["tenantID"]);return Object.assign(Object.assign({},n),{externalId:t})};async function registrationCodeCreate(e,t,n,r={permanent:!1}){const{externalId:i}=r,s=__rest$1(r,["externalId"]);return remapRegistationCodeResult(await e.post("/v1/registration-codes",Object.assign(Object.assign({code:t,utilisationPeriods:"string"==typeof n?[n]:n},i?{tenantID:i}:{}),s)))}async function registrationCodeUpdateById(e,t,n){return remapRegistationCodeResult(await e.patch(`/v1/registration-codes/${t}`,n))}async function registrationCodeGetById(e,t){return remapRegistationCodeResult(await e.get(`/v1/invitations/${t}`))}async function registrationCodeDelete(e,t){return""===await e.delete(`/v1/invitations/${t}`)}async function serviceProviderCreate(e,t){return e.post("/v1/service-providers",t)}async function serviceProviderGetById(e,t){return e.get(`/v1/service-providers/${t}`)}async function serviceProviderUpdateById(e,t,n){return e.patch(`/v1/service-providers/${t}`,n)}var ETicketStatus,ETrafficLightColor,EnumUnitObjectType,EnumUnitType,EnumUserRelationType;async function ticketGetById(e,t){return e.get(`/v1/tickets/${t}`)}async function ticketCreateOnUser(e,t,n,r){return e.post(`/v1/users/${t}/tickets`,Object.assign(Object.assign({},r),{files:r.files?(await createManyFilesSorted(r.files,e)).success:[],utilisationPeriod:n}))}async function ticketCreateOnServiceProvider(e,t,n){return e.post(`/v1/property-managers/${t}/tickets`,Object.assign(Object.assign({},n),{files:n.files?(await createManyFilesSorted(n.files,e)).success:[]}))}async function unitCreate(e,t,n){return e.post(`/v1/groups/${t}/units`,n)}async function unitGetById(e,t){return e.get(`/v1/units/${t}`)}async function unitUpdateById(e,t,n){return e.patch(`/v1/units/${t}`,n)}async function getUnits(e,t=1,n=-1,r={}){const{_embedded:{items:i},total:s}=await e.get("/v1/units",{filter:JSON.stringify(r),limit:n,page:t});return{_embedded:{items:i},total:s}}async function userRelationCreate(e,t,n){return e.post(`/v1/users/${t}/user-relations/${n.type}`,{ids:n.ids,level:n.level,readOnly:n.readOnly,role:n.role})}async function userRelationDelete(e,t,n){return e.delete(`/v1/users/${t}/user-relations/${n.type}`,{ids:n.ids,level:n.level,role:n.role})}async function userRelationsGetByUser(e,t){return e.get(`/v1/users/${t}/user-relations`)}!function(e){e.CLOSED="closed",e.WAITING_FOR_AGENT="waiting-for-agent",e.WAITING_FOR_CUSTOMER="waiting-for-customer",e.WAITING_FOR_EXTERNAL="waiting-for-external"}(ETicketStatus||(ETicketStatus={})),function(e){e.GREEN="green",e.RED="red",e.YELLOW="yellow"}(ETrafficLightColor||(ETrafficLightColor={})),exports.EnumUnitObjectType=void 0,EnumUnitObjectType=exports.EnumUnitObjectType||(exports.EnumUnitObjectType={}),EnumUnitObjectType.adjoiningRoom="adjoining-room",EnumUnitObjectType.advertisingSpace="advertising-space",EnumUnitObjectType.aerial="aerial",EnumUnitObjectType.apartmentBuilding="apartment-building",EnumUnitObjectType.atm="atm",EnumUnitObjectType.atmRoom="atm-room",EnumUnitObjectType.attic="attic",EnumUnitObjectType.atticFlat="attic-flat",EnumUnitObjectType.bank="bank",EnumUnitObjectType.basment="basment",EnumUnitObjectType.bikeShed="bike-shed",EnumUnitObjectType.buildingLaw="building-law",EnumUnitObjectType.cafeteria="cafeteria",EnumUnitObjectType.caretakerRoom="caretaker-room",EnumUnitObjectType.carport="carport",EnumUnitObjectType.cellar="cellar",EnumUnitObjectType.commercialProperty="commercial-property",EnumUnitObjectType.commonRoom="common-room",EnumUnitObjectType.deliveryZone="delivery-zone",EnumUnitObjectType.diverse="diverse",EnumUnitObjectType.doubleParkingSpace="double-parking-space",EnumUnitObjectType.engineeringRoom="engineering-room",EnumUnitObjectType.entertainment="entertainment",EnumUnitObjectType.environment="environment",EnumUnitObjectType.estate="estate",EnumUnitObjectType.fillingStation="filling-station",EnumUnitObjectType.fitnessCenter="fitness-center",EnumUnitObjectType.flat="flat",EnumUnitObjectType.freeZone="free-zone",EnumUnitObjectType.garage="garage",EnumUnitObjectType.garden="garden",EnumUnitObjectType.gardenFlat="garden-flat",EnumUnitObjectType.heatingFacilities="heating-facilities",EnumUnitObjectType.hotel="hotel",EnumUnitObjectType.incidentalRentalExpenses="incidental-rental-expenses",EnumUnitObjectType.industry="industry",EnumUnitObjectType.kiosk="kiosk",EnumUnitObjectType.kitchen="kitchen",EnumUnitObjectType.loft="loft",EnumUnitObjectType.machine="machine",EnumUnitObjectType.maisonette="maisonette",EnumUnitObjectType.medicalPractice="medical-practice",EnumUnitObjectType.mopedShed="moped-shed",EnumUnitObjectType.motorcycleParkingSpace="motorcycle-parking-space",EnumUnitObjectType.office="office",EnumUnitObjectType.oneFamilyHouse="one-family-house",EnumUnitObjectType.parkingBox="parking-box",EnumUnitObjectType.parkingGarage="parking-garage",EnumUnitObjectType.parkingSpace="parking-space",EnumUnitObjectType.parkingSpaces="parking-spaces",EnumUnitObjectType.penthouse="penthouse",EnumUnitObjectType.productionPlant="production-plant",EnumUnitObjectType.pub="pub",EnumUnitObjectType.publicArea="public-area",EnumUnitObjectType.restaurant="restaurant",EnumUnitObjectType.retirementHome="retirement-home",EnumUnitObjectType.salesFloor="sales-floor",EnumUnitObjectType.school="school",EnumUnitObjectType.shelter="shelter",EnumUnitObjectType.storage="storage",EnumUnitObjectType.store="store",EnumUnitObjectType.storeroom="storeroom",EnumUnitObjectType.studio="studio",EnumUnitObjectType.terrace="terrace",EnumUnitObjectType.toilets="toilets",EnumUnitObjectType.utilityRoom="utility-room",EnumUnitObjectType.variableParkingSpace="variable-parking-space",EnumUnitObjectType.variableRoom="variable-room",EnumUnitObjectType.visitorParkingSpace="visitor-parking-space",EnumUnitObjectType.workshop="workshop",exports.EnumUnitType=void 0,EnumUnitType=exports.EnumUnitType||(exports.EnumUnitType={}),EnumUnitType.rented="rented",EnumUnitType.owned="owned",exports.EnumUserRelationType=void 0,EnumUserRelationType=exports.EnumUserRelationType||(exports.EnumUserRelationType={}),EnumUserRelationType.isResponsible="is-responsible";var __rest=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n},EnumUtilisationPeriodType;async function utilisationPeriodCreate(e,t,n){const r=await e.post(`/v1/units/${t}/utilisation-periods`,n),{tenantIDs:i,_embedded:s}=r,o=__rest(r,["tenantIDs","_embedded"]);return Object.assign(Object.assign({},o),{invitations:s.invitations.map(remapRegistationCodeResult),tenantIds:i,users:remapEmbeddedUser(s)})}async function utilisationPeriodGetById(e,t){const n=await e.get(`/v1/utilisation-periods/${t}`),{tenantIDs:r,_embedded:i}=n,s=__rest(n,["tenantIDs","_embedded"]);return Object.assign(Object.assign({},s),{invitations:i.invitations.map(remapRegistationCodeResult),tenantIds:r,users:remapEmbeddedUser(i)})}async function utilisationPeriodUpdateById(e,t,n){const r=await e.patch(`/v1/utilisation-periods/${t}`,n),{tenantIDs:i,_embedded:s}=r,o=__rest(r,["tenantIDs","_embedded"]);return Object.assign(Object.assign({},o),{invitations:s.invitations.map(remapRegistationCodeResult),tenantIds:i,users:remapEmbeddedUser(s)})}async function utilisationPeriodDelete(e,t){return!await e.delete(`/v1/utilisation-periods/${t}/soft`)}async function utilisationPeriodCheckInUser(e,t,n){return await e.post(`/v1/utilisation-periods/${t}/users`,{email:n.email})&&e.utilisationPeriodGetById(t)}async function utilisationPeriodCheckOutUser(e,t,n){return""===await e.delete(`/v1/utilisation-periods/${t}/users/${n}`)}async function utilisationPeriodAddRegistrationCode(e,t,n,r,i=!1){return e.post(`/v1/utilisation-periods/${t}/registration-codes`,{code:n,permanent:i,tenant:r})}async function patch(e,t,n,r){return e("patch",t,{body:n},r)}async function post(e,t,n,r){return e("post",t,{body:n},r)}async function put(e,t,n,r){return e("put",t,{body:n},r)}exports.EnumUtilisationPeriodType=void 0,EnumUtilisationPeriodType=exports.EnumUtilisationPeriodType||(exports.EnumUtilisationPeriodType={}),EnumUtilisationPeriodType.tenant="tenant",EnumUtilisationPeriodType.ownership="ownership",EnumUtilisationPeriodType.vacant="vacant";var load=function(e,t,n={}){var r,i,s;for(r in t)s=t[r],n[r]=null!=(i=e[r])?i:s;return n},overwrite=function(e,t,n={}){var r,i;for(r in e)i=e[r],void 0!==t[r]&&(n[r]=i);return n},parser$8={load:load,overwrite:overwrite},DLList$2;DLList$2=class{constructor(e,t){this.incr=e,this.decr=t,this._first=null,this._last=null,this.length=0}push(e){var t;this.length++,"function"==typeof this.incr&&this.incr(),t={value:e,prev:this._last,next:null},null!=this._last?(this._last.next=t,this._last=t):this._first=this._last=t}shift(){var e;if(null!=this._first)return this.length--,"function"==typeof this.decr&&this.decr(),e=this._first.value,null!=(this._first=this._first.next)?this._first.prev=null:this._last=null,e}first(){if(null!=this._first)return this._first.value}getArray(){var e,t,n;for(e=this._first,n=[];null!=e;)n.push((t=e,e=e.next,t.value));return n}forEachShift(e){var t;for(t=this.shift();null!=t;)e(t),t=this.shift()}debug(){var e,t,n,r,i;for(e=this._first,i=[];null!=e;)i.push((t=e,e=e.next,{value:t.value,prev:null!=(n=t.prev)?n.value:void 0,next:null!=(r=t.next)?r.value:void 0}));return i}};var DLList_1=DLList$2,Events$6;function asyncGeneratorStep$8(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$8(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$8(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$8(s,r,i,o,a,"throw",e)}o(void 0)}))}}Events$6=class{constructor(e){if(this.instance=e,this._events={},null!=this.instance.on||null!=this.instance.once||null!=this.instance.removeAllListeners)throw new Error("An Emitter already exists for this object");this.instance.on=(e,t)=>this._addListener(e,"many",t),this.instance.once=(e,t)=>this._addListener(e,"once",t),this.instance.removeAllListeners=(e=null)=>null!=e?delete this._events[e]:this._events={}}_addListener(e,t,n){var r;return null==(r=this._events)[e]&&(r[e]=[]),this._events[e].push({cb:n,status:t}),this.instance}listenerCount(e){return null!=this._events[e]?this._events[e].length:0}trigger(e,...t){var n=this;return _asyncToGenerator$8((function*(){var r,i;try{if("debug"!==e&&n.trigger("debug",`Event triggered: ${e}`,t),null==n._events[e])return;return n._events[e]=n._events[e].filter((function(e){return"none"!==e.status})),i=n._events[e].map(function(){var e=_asyncToGenerator$8((function*(e){var r,i;if("none"!==e.status){"once"===e.status&&(e.status="none");try{return"function"==typeof(null!=(i="function"==typeof e.cb?e.cb(...t):void 0)?i.then:void 0)?yield i:i}catch(e){return r=e,n.trigger("error",r),null}}}));return function(t){return e.apply(this,arguments)}}()),(yield Promise.all(i)).find((function(e){return null!=e}))}catch(e){return r=e,n.trigger("error",r),null}}))()}};var Events_1=Events$6,DLList$1,Events$5,Queues$1;DLList$1=DLList_1,Events$5=Events_1,Queues$1=class{constructor(e){this.Events=new Events$5(this),this._length=0,this._lists=function(){var t,n,r;for(r=[],t=1,n=e;1<=n?t<=n:t>=n;1<=n?++t:--t)r.push(new DLList$1((()=>this.incr()),(()=>this.decr())));return r}.call(this)}incr(){if(0==this._length++)return this.Events.trigger("leftzero")}decr(){if(0==--this._length)return this.Events.trigger("zero")}push(e){return this._lists[e.options.priority].push(e)}queued(e){return null!=e?this._lists[e].length:this._length}shiftAll(e){return this._lists.forEach((function(t){return t.forEachShift(e)}))}getFirst(e=this._lists){var t,n,r;for(t=0,n=e.length;t<n;t++)if((r=e[t]).length>0)return r;return[]}shiftLastFrom(e){return this.getFirst(this._lists.slice(e).reverse()).shift()}};var Queues_1=Queues$1,BottleneckError$4;BottleneckError$4=class extends Error{};var BottleneckError_1=BottleneckError$4,BottleneckError$3,DEFAULT_PRIORITY$1,Job$1,NUM_PRIORITIES$1,parser$7;function asyncGeneratorStep$7(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$7(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$7(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$7(s,r,i,o,a,"throw",e)}o(void 0)}))}}NUM_PRIORITIES$1=10,DEFAULT_PRIORITY$1=5,parser$7=parser$8,BottleneckError$3=BottleneckError_1,Job$1=class{constructor(e,t,n,r,i,s,o,a){this.task=e,this.args=t,this.rejectOnDrop=i,this.Events=s,this._states=o,this.Promise=a,this.options=parser$7.load(n,r),this.options.priority=this._sanitizePriority(this.options.priority),this.options.id===r.id&&(this.options.id=`${this.options.id}-${this._randomIndex()}`),this.promise=new this.Promise(((e,t)=>{this._resolve=e,this._reject=t})),this.retryCount=0}_sanitizePriority(e){var t;return(t=~~e!==e?DEFAULT_PRIORITY$1:e)<0?0:t>NUM_PRIORITIES$1-1?NUM_PRIORITIES$1-1:t}_randomIndex(){return Math.random().toString(36).slice(2)}doDrop({error:e,message:t="This job has been dropped by Bottleneck"}={}){return!!this._states.remove(this.options.id)&&(this.rejectOnDrop&&this._reject(null!=e?e:new BottleneckError$3(t)),this.Events.trigger("dropped",{args:this.args,options:this.options,task:this.task,promise:this.promise}),!0)}_assertStatus(e){var t;if((t=this._states.jobStatus(this.options.id))!==e&&("DONE"!==e||null!==t))throw new BottleneckError$3(`Invalid job status ${t}, expected ${e}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`)}doReceive(){return this._states.start(this.options.id),this.Events.trigger("received",{args:this.args,options:this.options})}doQueue(e,t){return this._assertStatus("RECEIVED"),this._states.next(this.options.id),this.Events.trigger("queued",{args:this.args,options:this.options,reachedHWM:e,blocked:t})}doRun(){return 0===this.retryCount?(this._assertStatus("QUEUED"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),this.Events.trigger("scheduled",{args:this.args,options:this.options})}doExecute(e,t,n,r){var i=this;return _asyncToGenerator$7((function*(){var s,o,a;0===i.retryCount?(i._assertStatus("RUNNING"),i._states.next(i.options.id)):i._assertStatus("EXECUTING"),o={args:i.args,options:i.options,retryCount:i.retryCount},i.Events.trigger("executing",o);try{if(a=yield null!=e?e.schedule(i.options,i.task,...i.args):i.task(...i.args),t())return i.doDone(o),yield r(i.options,o),i._assertStatus("DONE"),i._resolve(a)}catch(e){return s=e,i._onFailure(s,o,t,n,r)}}))()}doExpire(e,t,n){var r,i;return this._states.jobStatus("RUNNING"===this.options.id)&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),i={args:this.args,options:this.options,retryCount:this.retryCount},r=new BottleneckError$3(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(r,i,e,t,n)}_onFailure(e,t,n,r,i){var s=this;return _asyncToGenerator$7((function*(){var o,a;if(n())return null!=(o=yield s.Events.trigger("failed",e,t))?(a=~~o,s.Events.trigger("retry",`Retrying ${s.options.id} after ${a} ms`,t),s.retryCount++,r(a)):(s.doDone(t),yield i(s.options,t),s._assertStatus("DONE"),s._reject(e))}))()}doDone(e){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",e)}};var Job_1=Job$1,BottleneckError$2,LocalDatastore$1,parser$6;function asyncGeneratorStep$6(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$6(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$6(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$6(s,r,i,o,a,"throw",e)}o(void 0)}))}}parser$6=parser$8,BottleneckError$2=BottleneckError_1,LocalDatastore$1=class{constructor(e,t,n){this.instance=e,this.storeOptions=t,this.clientId=this.instance._randomIndex(),parser$6.load(n,n,this),this._nextRequest=this._lastReservoirRefresh=this._lastReservoirIncrease=Date.now(),this._running=0,this._done=0,this._unblockTime=0,this.ready=this.Promise.resolve(),this.clients={},this._startHeartbeat()}_startHeartbeat(){var e;return null==this.heartbeat&&(null!=this.storeOptions.reservoirRefreshInterval&&null!=this.storeOptions.reservoirRefreshAmount||null!=this.storeOptions.reservoirIncreaseInterval&&null!=this.storeOptions.reservoirIncreaseAmount)?"function"==typeof(e=this.heartbeat=setInterval((()=>{var e,t,n,r,i;if(r=Date.now(),null!=this.storeOptions.reservoirRefreshInterval&&r>=this._lastReservoirRefresh+this.storeOptions.reservoirRefreshInterval&&(this._lastReservoirRefresh=r,this.storeOptions.reservoir=this.storeOptions.reservoirRefreshAmount,this.instance._drainAll(this.computeCapacity())),null!=this.storeOptions.reservoirIncreaseInterval&&r>=this._lastReservoirIncrease+this.storeOptions.reservoirIncreaseInterval){var s=this.storeOptions;if(e=s.reservoirIncreaseAmount,n=s.reservoirIncreaseMaximum,i=s.reservoir,this._lastReservoirIncrease=r,(t=null!=n?Math.min(e,n-i):e)>0)return this.storeOptions.reservoir+=t,this.instance._drainAll(this.computeCapacity())}}),this.heartbeatInterval)).unref?e.unref():void 0:clearInterval(this.heartbeat)}__publish__(e){var t=this;return _asyncToGenerator$6((function*(){return yield t.yieldLoop(),t.instance.Events.trigger("message",e.toString())}))()}__disconnect__(e){var t=this;return _asyncToGenerator$6((function*(){return yield t.yieldLoop(),clearInterval(t.heartbeat),t.Promise.resolve()}))()}yieldLoop(e=0){return new this.Promise((function(t,n){return setTimeout(t,e)}))}computePenalty(){var e;return null!=(e=this.storeOptions.penalty)?e:15*this.storeOptions.minTime||5e3}__updateSettings__(e){var t=this;return _asyncToGenerator$6((function*(){return yield t.yieldLoop(),parser$6.overwrite(e,e,t.storeOptions),t._startHeartbeat(),t.instance._drainAll(t.computeCapacity()),!0}))()}__running__(){var e=this;return _asyncToGenerator$6((function*(){return yield e.yieldLoop(),e._running}))()}__queued__(){var e=this;return _asyncToGenerator$6((function*(){return yield e.yieldLoop(),e.instance.queued()}))()}__done__(){var e=this;return _asyncToGenerator$6((function*(){return yield e.yieldLoop(),e._done}))()}__groupCheck__(e){var t=this;return _asyncToGenerator$6((function*(){return yield t.yieldLoop(),t._nextRequest+t.timeout<e}))()}computeCapacity(){var e,t,n=this.storeOptions;return e=n.maxConcurrent,t=n.reservoir,null!=e&&null!=t?Math.min(e-this._running,t):null!=e?e-this._running:null!=t?t:null}conditionsCheck(e){var t;return null==(t=this.computeCapacity())||e<=t}__incrementReservoir__(e){var t=this;return _asyncToGenerator$6((function*(){var n;return yield t.yieldLoop(),n=t.storeOptions.reservoir+=e,t.instance._drainAll(t.computeCapacity()),n}))()}__currentReservoir__(){var e=this;return _asyncToGenerator$6((function*(){return yield e.yieldLoop(),e.storeOptions.reservoir}))()}isBlocked(e){return this._unblockTime>=e}check(e,t){return this.conditionsCheck(e)&&this._nextRequest-t<=0}__check__(e){var t=this;return _asyncToGenerator$6((function*(){var n;return yield t.yieldLoop(),n=Date.now(),t.check(e,n)}))()}__register__(e,t,n){var r=this;return _asyncToGenerator$6((function*(){var e,n;return yield r.yieldLoop(),e=Date.now(),r.conditionsCheck(t)?(r._running+=t,null!=r.storeOptions.reservoir&&(r.storeOptions.reservoir-=t),n=Math.max(r._nextRequest-e,0),r._nextRequest=e+n+r.storeOptions.minTime,{success:!0,wait:n,reservoir:r.storeOptions.reservoir}):{success:!1}}))()}strategyIsBlock(){return 3===this.storeOptions.strategy}__submit__(e,t){var n=this;return _asyncToGenerator$6((function*(){var r,i,s;if(yield n.yieldLoop(),null!=n.storeOptions.maxConcurrent&&t>n.storeOptions.maxConcurrent)throw new BottleneckError$2(`Impossible to add a job having a weight of ${t} to a limiter having a maxConcurrent setting of ${n.storeOptions.maxConcurrent}`);return i=Date.now(),s=null!=n.storeOptions.highWater&&e===n.storeOptions.highWater&&!n.check(t,i),(r=n.strategyIsBlock()&&(s||n.isBlocked(i)))&&(n._unblockTime=i+n.computePenalty(),n._nextRequest=n._unblockTime+n.storeOptions.minTime,n.instance._dropAllQueued()),{reachedHWM:s,blocked:r,strategy:n.storeOptions.strategy}}))()}__free__(e,t){var n=this;return _asyncToGenerator$6((function*(){return yield n.yieldLoop(),n._running-=t,n._done+=t,n.instance._drainAll(n.computeCapacity()),{running:n._running}}))()}};var LocalDatastore_1=LocalDatastore$1,lua={"blacklist_client.lua":"local blacklist = ARGV[num_static_argv + 1]\n\nif redis.call('zscore', client_last_seen_key, blacklist) then\n redis.call('zadd', client_last_seen_key, 0, blacklist)\nend\n\n\nreturn {}\n","check.lua":"local weight = tonumber(ARGV[num_static_argv + 1])\n\nlocal capacity = process_tick(now, false)['capacity']\nlocal nextRequest = tonumber(redis.call('hget', settings_key, 'nextRequest'))\n\nreturn conditions_check(capacity, weight) and nextRequest - now <= 0\n","conditions_check.lua":"local conditions_check = function (capacity, weight)\n return capacity == nil or weight <= capacity\nend\n","current_reservoir.lua":"return process_tick(now, false)['reservoir']\n","done.lua":"process_tick(now, false)\n\nreturn tonumber(redis.call('hget', settings_key, 'done'))\n","free.lua":"local index = ARGV[num_static_argv + 1]\n\nredis.call('zadd', job_expirations_key, 0, index)\n\nreturn process_tick(now, false)['running']\n","get_time.lua":"redis.replicate_commands()\n\nlocal get_time = function ()\n local time = redis.call('time')\n\n return tonumber(time[1]..string.sub(time[2], 1, 3))\nend\n","group_check.lua":"return not (redis.call('exists', settings_key) == 1)\n","heartbeat.lua":"process_tick(now, true)\n","increment_reservoir.lua":"local incr = tonumber(ARGV[num_static_argv + 1])\n\nredis.call('hincrby', settings_key, 'reservoir', incr)\n\nlocal reservoir = process_tick(now, true)['reservoir']\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn reservoir\n","init.lua":"local clear = tonumber(ARGV[num_static_argv + 1])\nlocal limiter_version = ARGV[num_static_argv + 2]\nlocal num_local_argv = num_static_argv + 2\n\nif clear == 1 then\n redis.call('del', unpack(KEYS))\nend\n\nif redis.call('exists', settings_key) == 0 then\n -- Create\n local args = {'hmset', settings_key}\n\n for i = num_local_argv + 1, #ARGV do\n table.insert(args, ARGV[i])\n end\n\n redis.call(unpack(args))\n redis.call('hmset', settings_key,\n 'nextRequest', now,\n 'lastReservoirRefresh', now,\n 'lastReservoirIncrease', now,\n 'running', 0,\n 'done', 0,\n 'unblockTime', 0,\n 'capacityPriorityCounter', 0\n )\n\nelse\n -- Apply migrations\n local settings = redis.call('hmget', settings_key,\n 'id',\n 'version'\n )\n local id = settings[1]\n local current_version = settings[2]\n\n if current_version ~= limiter_version then\n local version_digits = {}\n for k, v in string.gmatch(current_version, \"([^.]+)\") do\n table.insert(version_digits, tonumber(k))\n end\n\n -- 2.10.0\n if version_digits[2] < 10 then\n redis.call('hsetnx', settings_key, 'reservoirRefreshInterval', '')\n redis.call('hsetnx', settings_key, 'reservoirRefreshAmount', '')\n redis.call('hsetnx', settings_key, 'lastReservoirRefresh', '')\n redis.call('hsetnx', settings_key, 'done', 0)\n redis.call('hset', settings_key, 'version', '2.10.0')\n end\n\n -- 2.11.1\n if version_digits[2] < 11 or (version_digits[2] == 11 and version_digits[3] < 1) then\n if redis.call('hstrlen', settings_key, 'lastReservoirRefresh') == 0 then\n redis.call('hmset', settings_key,\n 'lastReservoirRefresh', now,\n 'version', '2.11.1'\n )\n end\n end\n\n -- 2.14.0\n if version_digits[2] < 14 then\n local old_running_key = 'b_'..id..'_running'\n local old_executing_key = 'b_'..id..'_executing'\n\n if redis.call('exists', old_running_key) == 1 then\n redis.call('rename', old_running_key, job_weights_key)\n end\n if redis.call('exists', old_executing_key) == 1 then\n redis.call('rename', old_executing_key, job_expirations_key)\n end\n redis.call('hset', settings_key, 'version', '2.14.0')\n end\n\n -- 2.15.2\n if version_digits[2] < 15 or (version_digits[2] == 15 and version_digits[3] < 2) then\n redis.call('hsetnx', settings_key, 'capacityPriorityCounter', 0)\n redis.call('hset', settings_key, 'version', '2.15.2')\n end\n\n -- 2.17.0\n if version_digits[2] < 17 then\n redis.call('hsetnx', settings_key, 'clientTimeout', 10000)\n redis.call('hset', settings_key, 'version', '2.17.0')\n end\n\n -- 2.18.0\n if version_digits[2] < 18 then\n redis.call('hsetnx', settings_key, 'reservoirIncreaseInterval', '')\n redis.call('hsetnx', settings_key, 'reservoirIncreaseAmount', '')\n redis.call('hsetnx', settings_key, 'reservoirIncreaseMaximum', '')\n redis.call('hsetnx', settings_key, 'lastReservoirIncrease', now)\n redis.call('hset', settings_key, 'version', '2.18.0')\n end\n\n end\n\n process_tick(now, false)\nend\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn {}\n","process_tick.lua":"local process_tick = function (now, always_publish)\n\n local compute_capacity = function (maxConcurrent, running, reservoir)\n if maxConcurrent ~= nil and reservoir ~= nil then\n return math.min((maxConcurrent - running), reservoir)\n elseif maxConcurrent ~= nil then\n return maxConcurrent - running\n elseif reservoir ~= nil then\n return reservoir\n else\n return nil\n end\n end\n\n local settings = redis.call('hmget', settings_key,\n 'id',\n 'maxConcurrent',\n 'running',\n 'reservoir',\n 'reservoirRefreshInterval',\n 'reservoirRefreshAmount',\n 'lastReservoirRefresh',\n 'reservoirIncreaseInterval',\n 'reservoirIncreaseAmount',\n 'reservoirIncreaseMaximum',\n 'lastReservoirIncrease',\n 'capacityPriorityCounter',\n 'clientTimeout'\n )\n local id = settings[1]\n local maxConcurrent = tonumber(settings[2])\n local running = tonumber(settings[3])\n local reservoir = tonumber(settings[4])\n local reservoirRefreshInterval = tonumber(settings[5])\n local reservoirRefreshAmount = tonumber(settings[6])\n local lastReservoirRefresh = tonumber(settings[7])\n local reservoirIncreaseInterval = tonumber(settings[8])\n local reservoirIncreaseAmount = tonumber(settings[9])\n local reservoirIncreaseMaximum = tonumber(settings[10])\n local lastReservoirIncrease = tonumber(settings[11])\n local capacityPriorityCounter = tonumber(settings[12])\n local clientTimeout = tonumber(settings[13])\n\n local initial_capacity = compute_capacity(maxConcurrent, running, reservoir)\n\n --\n -- Process 'running' changes\n --\n local expired = redis.call('zrangebyscore', job_expirations_key, '-inf', '('..now)\n\n if #expired > 0 then\n redis.call('zremrangebyscore', job_expirations_key, '-inf', '('..now)\n\n local flush_batch = function (batch, acc)\n local weights = redis.call('hmget', job_weights_key, unpack(batch))\n redis.call('hdel', job_weights_key, unpack(batch))\n local clients = redis.call('hmget', job_clients_key, unpack(batch))\n redis.call('hdel', job_clients_key, unpack(batch))\n\n -- Calculate sum of removed weights\n for i = 1, #weights do\n acc['total'] = acc['total'] + (tonumber(weights[i]) or 0)\n end\n\n -- Calculate sum of removed weights by client\n local client_weights = {}\n for i = 1, #clients do\n local removed = tonumber(weights[i]) or 0\n if removed > 0 then\n acc['client_weights'][clients[i]] = (acc['client_weights'][clients[i]] or 0) + removed\n end\n end\n end\n\n local acc = {\n ['total'] = 0,\n ['client_weights'] = {}\n }\n local batch_size = 1000\n\n -- Compute changes to Zsets and apply changes to Hashes\n for i = 1, #expired, batch_size do\n local batch = {}\n for j = i, math.min(i + batch_size - 1, #expired) do\n table.insert(batch, expired[j])\n end\n\n flush_batch(batch, acc)\n end\n\n -- Apply changes to Zsets\n if acc['total'] > 0 then\n redis.call('hincrby', settings_key, 'done', acc['total'])\n running = tonumber(redis.call('hincrby', settings_key, 'running', -acc['total']))\n end\n\n for client, weight in pairs(acc['client_weights']) do\n redis.call('zincrby', client_running_key, -weight, client)\n end\n end\n\n --\n -- Process 'reservoir' changes\n --\n local reservoirRefreshActive = reservoirRefreshInterval ~= nil and reservoirRefreshAmount ~= nil\n if reservoirRefreshActive and now >= lastReservoirRefresh + reservoirRefreshInterval then\n reservoir = reservoirRefreshAmount\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'lastReservoirRefresh', now\n )\n end\n\n local reservoirIncreaseActive = reservoirIncreaseInterval ~= nil and reservoirIncreaseAmount ~= nil\n if reservoirIncreaseActive and now >= lastReservoirIncrease + reservoirIncreaseInterval then\n local num_intervals = math.floor((now - lastReservoirIncrease) / reservoirIncreaseInterval)\n local incr = reservoirIncreaseAmount * num_intervals\n if reservoirIncreaseMaximum ~= nil then\n incr = math.min(incr, reservoirIncreaseMaximum - (reservoir or 0))\n end\n if incr > 0 then\n reservoir = (reservoir or 0) + incr\n end\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'lastReservoirIncrease', lastReservoirIncrease + (num_intervals * reservoirIncreaseInterval)\n )\n end\n\n --\n -- Clear unresponsive clients\n --\n local unresponsive = redis.call('zrangebyscore', client_last_seen_key, '-inf', (now - clientTimeout))\n local unresponsive_lookup = {}\n local terminated_clients = {}\n for i = 1, #unresponsive do\n unresponsive_lookup[unresponsive[i]] = true\n if tonumber(redis.call('zscore', client_running_key, unresponsive[i])) == 0 then\n table.insert(terminated_clients, unresponsive[i])\n end\n end\n if #terminated_clients > 0 then\n redis.call('zrem', client_running_key, unpack(terminated_clients))\n redis.call('hdel', client_num_queued_key, unpack(terminated_clients))\n redis.call('zrem', client_last_registered_key, unpack(terminated_clients))\n redis.call('zrem', client_last_seen_key, unpack(terminated_clients))\n end\n\n --\n -- Broadcast capacity changes\n --\n local final_capacity = compute_capacity(maxConcurrent, running, reservoir)\n\n if always_publish or (initial_capacity ~= nil and final_capacity == nil) then\n -- always_publish or was not unlimited, now unlimited\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\n\n elseif initial_capacity ~= nil and final_capacity ~= nil and final_capacity > initial_capacity then\n -- capacity was increased\n -- send the capacity message to the limiter having the lowest number of running jobs\n -- the tiebreaker is the limiter having not registered a job in the longest time\n\n local lowest_concurrency_value = nil\n local lowest_concurrency_clients = {}\n local lowest_concurrency_last_registered = {}\n local client_concurrencies = redis.call('zrange', client_running_key, 0, -1, 'withscores')\n\n for i = 1, #client_concurrencies, 2 do\n local client = client_concurrencies[i]\n local concurrency = tonumber(client_concurrencies[i+1])\n\n if (\n lowest_concurrency_value == nil or lowest_concurrency_value == concurrency\n ) and (\n not unresponsive_lookup[client]\n ) and (\n tonumber(redis.call('hget', client_num_queued_key, client)) > 0\n ) then\n lowest_concurrency_value = concurrency\n table.insert(lowest_concurrency_clients, client)\n local last_registered = tonumber(redis.call('zscore', client_last_registered_key, client))\n table.insert(lowest_concurrency_last_registered, last_registered)\n end\n end\n\n if #lowest_concurrency_clients > 0 then\n local position = 1\n local earliest = lowest_concurrency_last_registered[1]\n\n for i,v in ipairs(lowest_concurrency_last_registered) do\n if v < earliest then\n position = i\n earliest = v\n end\n end\n\n local next_client = lowest_concurrency_clients[position]\n redis.call('publish', 'b_'..id,\n 'capacity-priority:'..(final_capacity or '')..\n ':'..next_client..\n ':'..capacityPriorityCounter\n )\n redis.call('hincrby', settings_key, 'capacityPriorityCounter', '1')\n else\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\n end\n end\n\n return {\n ['capacity'] = final_capacity,\n ['running'] = running,\n ['reservoir'] = reservoir\n }\nend\n","queued.lua":"local clientTimeout = tonumber(redis.call('hget', settings_key, 'clientTimeout'))\nlocal valid_clients = redis.call('zrangebyscore', client_last_seen_key, (now - clientTimeout), 'inf')\nlocal client_queued = redis.call('hmget', client_num_queued_key, unpack(valid_clients))\n\nlocal sum = 0\nfor i = 1, #client_queued do\n sum = sum + tonumber(client_queued[i])\nend\n\nreturn sum\n","refresh_expiration.lua":"local refresh_expiration = function (now, nextRequest, groupTimeout)\n\n if groupTimeout ~= nil then\n local ttl = (nextRequest + groupTimeout) - now\n\n for i = 1, #KEYS do\n redis.call('pexpire', KEYS[i], ttl)\n end\n end\n\nend\n","refs.lua":"local settings_key = KEYS[1]\nlocal job_weights_key = KEYS[2]\nlocal job_expirations_key = KEYS[3]\nlocal job_clients_key = KEYS[4]\nlocal client_running_key = KEYS[5]\nlocal client_num_queued_key = KEYS[6]\nlocal client_last_registered_key = KEYS[7]\nlocal client_last_seen_key = KEYS[8]\n\nlocal now = tonumber(ARGV[1])\nlocal client = ARGV[2]\n\nlocal num_static_argv = 2\n","register.lua":"local index = ARGV[num_static_argv + 1]\nlocal weight = tonumber(ARGV[num_static_argv + 2])\nlocal expiration = tonumber(ARGV[num_static_argv + 3])\n\nlocal state = process_tick(now, false)\nlocal capacity = state['capacity']\nlocal reservoir = state['reservoir']\n\nlocal settings = redis.call('hmget', settings_key,\n 'nextRequest',\n 'minTime',\n 'groupTimeout'\n)\nlocal nextRequest = tonumber(settings[1])\nlocal minTime = tonumber(settings[2])\nlocal groupTimeout = tonumber(settings[3])\n\nif conditions_check(capacity, weight) then\n\n redis.call('hincrby', settings_key, 'running', weight)\n redis.call('hset', job_weights_key, index, weight)\n if expiration ~= nil then\n redis.call('zadd', job_expirations_key, now + expiration, index)\n end\n redis.call('hset', job_clients_key, index, client)\n redis.call('zincrby', client_running_key, weight, client)\n redis.call('hincrby', client_num_queued_key, client, -1)\n redis.call('zadd', client_last_registered_key, now, client)\n\n local wait = math.max(nextRequest - now, 0)\n local newNextRequest = now + wait + minTime\n\n if reservoir == nil then\n redis.call('hset', settings_key,\n 'nextRequest', newNextRequest\n )\n else\n reservoir = reservoir - weight\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'nextRequest', newNextRequest\n )\n end\n\n refresh_expiration(now, newNextRequest, groupTimeout)\n\n return {true, wait, reservoir}\n\nelse\n return {false}\nend\n","register_client.lua":"local queued = tonumber(ARGV[num_static_argv + 1])\n\n-- Could have been re-registered concurrently\nif not redis.call('zscore', client_last_seen_key, client) then\n redis.call('zadd', client_running_key, 0, client)\n redis.call('hset', client_num_queued_key, client, queued)\n redis.call('zadd', client_last_registered_key, 0, client)\nend\n\nredis.call('zadd', client_last_seen_key, now, client)\n\nreturn {}\n","running.lua":"return process_tick(now, false)['running']\n","submit.lua":"local queueLength = tonumber(ARGV[num_static_argv + 1])\nlocal weight = tonumber(ARGV[num_static_argv + 2])\n\nlocal capacity = process_tick(now, false)['capacity']\n\nlocal settings = redis.call('hmget', settings_key,\n 'id',\n 'maxConcurrent',\n 'highWater',\n 'nextRequest',\n 'strategy',\n 'unblockTime',\n 'penalty',\n 'minTime',\n 'groupTimeout'\n)\nlocal id = settings[1]\nlocal maxConcurrent = tonumber(settings[2])\nlocal highWater = tonumber(settings[3])\nlocal nextRequest = tonumber(settings[4])\nlocal strategy = tonumber(settings[5])\nlocal unblockTime = tonumber(settings[6])\nlocal penalty = tonumber(settings[7])\nlocal minTime = tonumber(settings[8])\nlocal groupTimeout = tonumber(settings[9])\n\nif maxConcurrent ~= nil and weight > maxConcurrent then\n return redis.error_reply('OVERWEIGHT:'..weight..':'..maxConcurrent)\nend\n\nlocal reachedHWM = (highWater ~= nil and queueLength == highWater\n and not (\n conditions_check(capacity, weight)\n and nextRequest - now <= 0\n )\n)\n\nlocal blocked = strategy == 3 and (reachedHWM or unblockTime >= now)\n\nif blocked then\n local computedPenalty = penalty\n if computedPenalty == nil then\n if minTime == 0 then\n computedPenalty = 5000\n else\n computedPenalty = 15 * minTime\n end\n end\n\n local newNextRequest = now + computedPenalty + minTime\n\n redis.call('hmset', settings_key,\n 'unblockTime', now + computedPenalty,\n 'nextRequest', newNextRequest\n )\n\n local clients_queued_reset = redis.call('hkeys', client_num_queued_key)\n local queued_reset = {}\n for i = 1, #clients_queued_reset do\n table.insert(queued_reset, clients_queued_reset[i])\n table.insert(queued_reset, 0)\n end\n redis.call('hmset', client_num_queued_key, unpack(queued_reset))\n\n redis.call('publish', 'b_'..id, 'blocked:')\n\n refresh_expiration(now, newNextRequest, groupTimeout)\nend\n\nif not blocked and not reachedHWM then\n redis.call('hincrby', client_num_queued_key, client, 1)\nend\n\nreturn {reachedHWM, blocked, strategy}\n","update_settings.lua":"local args = {'hmset', settings_key}\n\nfor i = num_static_argv + 1, #ARGV do\n table.insert(args, ARGV[i])\nend\n\nredis.call(unpack(args))\n\nprocess_tick(now, true)\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn {}\n","validate_client.lua":"if not redis.call('zscore', client_last_seen_key, client) then\n return redis.error_reply('UNKNOWN_CLIENT')\nend\n\nredis.call('zadd', client_last_seen_key, now, client)\n","validate_keys.lua":"if not (redis.call('exists', settings_key) == 1) then\n return redis.error_reply('SETTINGS_KEY_NOT_FOUND')\nend\n"},lua$1=Object.freeze({__proto__:null,default:lua}),require$$0$1=getCjsExportFromNamespace(lua$1),Scripts$3=createCommonjsModule((function(e,t){var n,r,i;n={refs:(r=require$$0$1)["refs.lua"],validate_keys:r["validate_keys.lua"],validate_client:r["validate_client.lua"],refresh_expiration:r["refresh_expiration.lua"],process_tick:r["process_tick.lua"],conditions_check:r["conditions_check.lua"],get_time:r["get_time.lua"]},t.allKeys=function(e){return[`b_${e}_settings`,`b_${e}_job_weights`,`b_${e}_job_expirations`,`b_${e}_job_clients`,`b_${e}_client_running`,`b_${e}_client_num_queued`,`b_${e}_client_last_registered`,`b_${e}_client_last_seen`]},i={init:{keys:t.allKeys,headers:["process_tick"],refresh_expiration:!0,code:r["init.lua"]},group_check:{keys:t.allKeys,headers:[],refresh_expiration:!1,code:r["group_check.lua"]},register_client:{keys:t.allKeys,headers:["validate_keys"],refresh_expiration:!1,code:r["register_client.lua"]},blacklist_client:{keys:t.allKeys,headers:["validate_keys","validate_client"],refresh_expiration:!1,code:r["blacklist_client.lua"]},heartbeat:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:r["heartbeat.lua"]},update_settings:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:r["update_settings.lua"]},running:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:r["running.lua"]},queued:{keys:t.allKeys,headers:["validate_keys","validate_client"],refresh_expiration:!1,code:r["queued.lua"]},done:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:r["done.lua"]},check:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!1,code:r["check.lua"]},submit:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!0,code:r["submit.lua"]},register:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!0,code:r["register.lua"]},free:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:r["free.lua"]},current_reservoir:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:r["current_reservoir.lua"]},increment_reservoir:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:r["increment_reservoir.lua"]}},t.names=Object.keys(i),t.keys=function(e,t){return i[e].keys(t)},t.payload=function(e){var t;return t=i[e],Array.prototype.concat(n.refs,t.headers.map((function(e){return n[e]})),t.refresh_expiration?n.refresh_expiration:"",t.code).join("\n")}})),Events$4,RedisConnection$2,Scripts$2,parser$5;function asyncGeneratorStep$5(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$5(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$5(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$5(s,r,i,o,a,"throw",e)}o(void 0)}))}}Scripts$3.allKeys,Scripts$3.names,Scripts$3.keys,Scripts$3.payload,parser$5=parser$8,Events$4=Events_1,Scripts$2=Scripts$3,RedisConnection$2=function(){class RedisConnection{constructor(options={}){parser$5.load(options,this.defaults,this),null==this.Redis&&(this.Redis=eval("require")("redis")),null==this.Events&&(this.Events=new Events$4(this)),this.terminated=!1,null==this.client&&(this.client=this.Redis.createClient(this.clientOptions)),this.subscriber=this.client.duplicate(),this.limiters={},this.shas={},this.ready=this.Promise.all([this._setup(this.client,!1),this._setup(this.subscriber,!0)]).then((()=>this._loadScripts())).then((()=>({client:this.client,subscriber:this.subscriber})))}_setup(e,t){return e.setMaxListeners(0),new this.Promise(((n,r)=>(e.on("error",(e=>this.Events.trigger("error",e))),t&&e.on("message",((e,t)=>{var n;return null!=(n=this.limiters[e])?n._store.onMessage(e,t):void 0})),e.ready?n():e.once("ready",n))))}_loadScript(e){return new this.Promise(((t,n)=>{var r;return r=Scripts$2.payload(e),this.client.multi([["script","load",r]]).exec(((r,i)=>null!=r?n(r):(this.shas[e]=i[0],t(i[0]))))}))}_loadScripts(){return this.Promise.all(Scripts$2.names.map((e=>this._loadScript(e))))}__runCommand__(e){var t=this;return _asyncToGenerator$5((function*(){return yield t.ready,new t.Promise(((n,r)=>t.client.multi([e]).exec_atomic((function(e,t){return null!=e?r(e):n(t[0])}))))}))()}__addLimiter__(e){return this.Promise.all([e.channel(),e.channel_client()].map((t=>new this.Promise(((n,r)=>{var i;return i=r=>{if(r===t)return this.subscriber.removeListener("subscribe",i),this.limiters[t]=e,n()},this.subscriber.on("subscribe",i),this.subscriber.subscribe(t)})))))}__removeLimiter__(e){var t=this;return this.Promise.all([e.channel(),e.channel_client()].map(function(){var e=_asyncToGenerator$5((function*(e){return t.terminated||(yield new t.Promise(((n,r)=>t.subscriber.unsubscribe(e,(function(t,i){return null!=t?r(t):i===e?n():void 0}))))),delete t.limiters[e]}));return function(t){return e.apply(this,arguments)}}()))}__scriptArgs__(e,t,n,r){var i;return i=Scripts$2.keys(e,t),[this.shas[e],i.length].concat(i,n,r)}__scriptFn__(e){return this.client.evalsha.bind(this.client)}disconnect(e=!0){var t,n,r,i;for(t=0,r=(i=Object.keys(this.limiters)).length;t<r;t++)n=i[t],clearInterval(this.limiters[n]._store.heartbeat);return this.limiters={},this.terminated=!0,this.client.end(e),this.subscriber.end(e),this.Promise.resolve()}}return RedisConnection.prototype.datastore="redis",RedisConnection.prototype.defaults={Redis:null,clientOptions:{},client:null,Promise:Promise,Events:null},RedisConnection}.call(void 0);var RedisConnection_1=RedisConnection$2,Events$3,IORedisConnection$2,Scripts$1,parser$4;function _slicedToArray$3(e,t){return _arrayWithHoles$3(e)||_iterableToArrayLimit$3(e,t)||_nonIterableRest$3()}function _nonIterableRest$3(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArrayLimit$3(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function _arrayWithHoles$3(e){if(Array.isArray(e))return e}function asyncGeneratorStep$4(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$4(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$4(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$4(s,r,i,o,a,"throw",e)}o(void 0)}))}}parser$4=parser$8,Events$3=Events_1,Scripts$1=Scripts$3,IORedisConnection$2=function(){class IORedisConnection{constructor(options={}){parser$4.load(options,this.defaults,this),null==this.Redis&&(this.Redis=eval("require")("ioredis")),null==this.Events&&(this.Events=new Events$3(this)),this.terminated=!1,null!=this.clusterNodes?(this.client=new this.Redis.Cluster(this.clusterNodes,this.clientOptions),this.subscriber=new this.Redis.Cluster(this.clusterNodes,this.clientOptions)):null!=this.client&&null==this.client.duplicate?this.subscriber=new this.Redis.Cluster(this.client.startupNodes,this.client.options):(null==this.client&&(this.client=new this.Redis(this.clientOptions)),this.subscriber=this.client.duplicate()),this.limiters={},this.ready=this.Promise.all([this._setup(this.client,!1),this._setup(this.subscriber,!0)]).then((()=>(this._loadScripts(),{client:this.client,subscriber:this.subscriber})))}_setup(e,t){return e.setMaxListeners(0),new this.Promise(((n,r)=>(e.on("error",(e=>this.Events.trigger("error",e))),t&&e.on("message",((e,t)=>{var n;return null!=(n=this.limiters[e])?n._store.onMessage(e,t):void 0})),"ready"===e.status?n():e.once("ready",n))))}_loadScripts(){return Scripts$1.names.forEach((e=>this.client.defineCommand(e,{lua:Scripts$1.payload(e)})))}__runCommand__(e){var t=this;return _asyncToGenerator$4((function*(){yield t.ready;var n=_slicedToArray$3(yield t.client.pipeline([e]).exec(),1),r=_slicedToArray$3(n[0],2);return r[0],r[1]}))()}__addLimiter__(e){return this.Promise.all([e.channel(),e.channel_client()].map((t=>new this.Promise(((n,r)=>this.subscriber.subscribe(t,(()=>(this.limiters[t]=e,n()))))))))}__removeLimiter__(e){var t=this;return[e.channel(),e.channel_client()].forEach(function(){var e=_asyncToGenerator$4((function*(e){return t.terminated||(yield t.subscriber.unsubscribe(e)),delete t.limiters[e]}));return function(t){return e.apply(this,arguments)}}())}__scriptArgs__(e,t,n,r){var i;return[(i=Scripts$1.keys(e,t)).length].concat(i,n,r)}__scriptFn__(e){return this.client[e].bind(this.client)}disconnect(e=!0){var t,n,r,i;for(t=0,r=(i=Object.keys(this.limiters)).length;t<r;t++)n=i[t],clearInterval(this.limiters[n]._store.heartbeat);return this.limiters={},this.terminated=!0,e?this.Promise.all([this.client.quit(),this.subscriber.quit()]):(this.client.disconnect(),this.subscriber.disconnect(),this.Promise.resolve())}}return IORedisConnection.prototype.datastore="ioredis",IORedisConnection.prototype.defaults={Redis:null,clientOptions:{},clusterNodes:null,client:null,Promise:Promise,Events:null},IORedisConnection}.call(void 0);var IORedisConnection_1=IORedisConnection$2,BottleneckError$1,IORedisConnection$1,RedisConnection$1,RedisDatastore$1,parser$3;function _slicedToArray$2(e,t){return _arrayWithHoles$2(e)||_iterableToArrayLimit$2(e,t)||_nonIterableRest$2()}function _nonIterableRest$2(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArrayLimit$2(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function _arrayWithHoles$2(e){if(Array.isArray(e))return e}function asyncGeneratorStep$3(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$3(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$3(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$3(s,r,i,o,a,"throw",e)}o(void 0)}))}}parser$3=parser$8,BottleneckError$1=BottleneckError_1,RedisConnection$1=RedisConnection_1,IORedisConnection$1=IORedisConnection_1,RedisDatastore$1=class{constructor(e,t,n){this.instance=e,this.storeOptions=t,this.originalId=this.instance.id,this.clientId=this.instance._randomIndex(),parser$3.load(n,n,this),this.clients={},this.capacityPriorityCounters={},this.sharedConnection=null!=this.connection,null==this.connection&&(this.connection="redis"===this.instance.datastore?new RedisConnection$1({Redis:this.Redis,clientOptions:this.clientOptions,Promise:this.Promise,Events:this.instance.Events}):"ioredis"===this.instance.datastore?new IORedisConnection$1({Redis:this.Redis,clientOptions:this.clientOptions,clusterNodes:this.clusterNodes,Promise:this.Promise,Events:this.instance.Events}):void 0),this.instance.connection=this.connection,this.instance.datastore=this.connection.datastore,this.ready=this.connection.ready.then((e=>(this.clients=e,this.runScript("init",this.prepareInitSettings(this.clearDatastore))))).then((()=>this.connection.__addLimiter__(this.instance))).then((()=>this.runScript("register_client",[this.instance.queued()]))).then((()=>{var e;return"function"==typeof(e=this.heartbeat=setInterval((()=>this.runScript("heartbeat",[]).catch((e=>this.instance.Events.trigger("error",e)))),this.heartbeatInterval)).unref&&e.unref(),this.clients}))}__publish__(e){var t=this;return _asyncToGenerator$3((function*(){return(yield t.ready).client.publish(t.instance.channel(),`message:${e.toString()}`)}))()}onMessage(e,t){var n=this;return _asyncToGenerator$3((function*(){var e,r,i,s,o,a,c,u,l,d;try{c=t.indexOf(":");var p=[t.slice(0,c),t.slice(c+1)];if(i=p[1],"capacity"===(d=p[0]))return yield n.instance._drainAll(i.length>0?~~i:void 0);if("capacity-priority"===d){var h=_slicedToArray$2(i.split(":"),3);return l=h[0],u=h[1],r=h[2],e=l.length>0?~~l:void 0,u===n.clientId?(s=yield n.instance._drainAll(e),a=null!=e?e-(s||0):"",yield n.clients.client.publish(n.instance.channel(),`capacity-priority:${a}::${r}`)):""===u?(clearTimeout(n.capacityPriorityCounters[r]),delete n.capacityPriorityCounters[r],n.instance._drainAll(e)):n.capacityPriorityCounters[r]=setTimeout(_asyncToGenerator$3((function*(){var t;try{return delete n.capacityPriorityCounters[r],yield n.runScript("blacklist_client",[u]),yield n.instance._drainAll(e)}catch(e){return t=e,n.instance.Events.trigger("error",t)}})),1e3)}if("message"===d)return n.instance.Events.trigger("message",i);if("blocked"===d)return yield n.instance._dropAllQueued()}catch(e){return o=e,n.instance.Events.trigger("error",o)}}))()}__disconnect__(e){return clearInterval(this.heartbeat),this.sharedConnection?this.connection.__removeLimiter__(this.instance):this.connection.disconnect(e)}runScript(e,t){var n=this;return _asyncToGenerator$3((function*(){return"init"!==e&&"register_client"!==e&&(yield n.ready),new n.Promise(((r,i)=>{var s,o;return s=[Date.now(),n.clientId].concat(t),n.instance.Events.trigger("debug",`Calling Redis script: ${e}.lua`,s),o=n.connection.__scriptArgs__(e,n.originalId,s,(function(e,t){return null!=e?i(e):r(t)})),n.connection.__scriptFn__(e)(...o)})).catch((r=>"SETTINGS_KEY_NOT_FOUND"===r.message?"heartbeat"===e?n.Promise.resolve():n.runScript("init",n.prepareInitSettings(!1)).then((()=>n.runScript(e,t))):"UNKNOWN_CLIENT"===r.message?n.runScript("register_client",[n.instance.queued()]).then((()=>n.runScript(e,t))):n.Promise.reject(r)))}))()}prepareArray(e){var t,n,r,i;for(r=[],t=0,n=e.length;t<n;t++)i=e[t],r.push(null!=i?i.toString():"");return r}prepareObject(e){var t,n,r;for(n in t=[],e)r=e[n],t.push(n,null!=r?r.toString():"");return t}prepareInitSettings(e){var t;return(t=this.prepareObject(Object.assign({},this.storeOptions,{id:this.originalId,version:this.instance.version,groupTimeout:this.timeout,clientTimeout:this.clientTimeout}))).unshift(e?1:0,this.instance.version),t}convertBool(e){return!!e}__updateSettings__(e){var t=this;return _asyncToGenerator$3((function*(){return yield t.runScript("update_settings",t.prepareObject(e)),parser$3.overwrite(e,e,t.storeOptions)}))()}__running__(){return this.runScript("running",[])}__queued__(){return this.runScript("queued",[])}__done__(){return this.runScript("done",[])}__groupCheck__(){var e=this;return _asyncToGenerator$3((function*(){return e.convertBool(yield e.runScript("group_check",[]))}))()}__incrementReservoir__(e){return this.runScript("increment_reservoir",[e])}__currentReservoir__(){return this.runScript("current_reservoir",[])}__check__(e){var t=this;return _asyncToGenerator$3((function*(){return t.convertBool(yield t.runScript("check",t.prepareArray([e])))}))()}__register__(e,t,n){var r=this;return _asyncToGenerator$3((function*(){var i,s,o,a=_slicedToArray$2(yield r.runScript("register",r.prepareArray([e,t,n])),3);return s=a[0],o=a[1],i=a[2],{success:r.convertBool(s),wait:o,reservoir:i}}))()}__submit__(e,t){var n=this;return _asyncToGenerator$3((function*(){var r,i,s,o,a;try{var c=_slicedToArray$2(yield n.runScript("submit",n.prepareArray([e,t])),3);return o=c[0],r=c[1],a=c[2],{reachedHWM:n.convertBool(o),blocked:n.convertBool(r),strategy:a}}catch(e){if(0===(i=e).message.indexOf("OVERWEIGHT")){var u=_slicedToArray$2(i.message.split(":"),3);throw u[0],t=u[1],s=u[2],new BottleneckError$1(`Impossible to add a job having a weight of ${t} to a limiter having a maxConcurrent setting of ${s}`)}throw i}}))()}__free__(e,t){var n=this;return _asyncToGenerator$3((function*(){return{running:yield n.runScript("free",n.prepareArray([e]))}}))()}};var RedisDatastore_1=RedisDatastore$1,BottleneckError,States$1;BottleneckError=BottleneckError_1,States$1=class{constructor(e){this.status=e,this._jobs={},this.counts=this.status.map((function(){return 0}))}next(e){var t,n;return n=(t=this._jobs[e])+1,null!=t&&n<this.status.length?(this.counts[t]--,this.counts[n]++,this._jobs[e]++):null!=t?(this.counts[t]--,delete this._jobs[e]):void 0}start(e){return 0,this._jobs[e]=0,this.counts[0]++}remove(e){var t;return null!=(t=this._jobs[e])&&(this.counts[t]--,delete this._jobs[e]),null!=t}jobStatus(e){var t;return null!=(t=this.status[this._jobs[e]])?t:null}statusJobs(e){var t,n,r,i;if(null!=e){if((n=this.status.indexOf(e))<0)throw new BottleneckError(`status must be one of ${this.status.join(", ")}`);for(t in i=[],r=this._jobs)r[t]===n&&i.push(t);return i}return Object.keys(this._jobs)}statusCounts(){return this.counts.reduce(((e,t,n)=>(e[this.status[n]]=t,e)),{})}};var States_1=States$1,DLList,Sync$1;function asyncGeneratorStep$2(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$2(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$2(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$2(s,r,i,o,a,"throw",e)}o(void 0)}))}}DLList=DLList_1,Sync$1=class{constructor(e,t){this.schedule=this.schedule.bind(this),this.name=e,this.Promise=t,this._running=0,this._queue=new DLList}isEmpty(){return 0===this._queue.length}_tryToRun(){var e=this;return _asyncToGenerator$2((function*(){var t,n,r,i,s,o,a;if(e._running<1&&e._queue.length>0){e._running++;var c=e._queue.shift();return a=c.task,t=c.args,s=c.resolve,i=c.reject,n=yield _asyncToGenerator$2((function*(){try{return o=yield a(...t),function(){return s(o)}}catch(e){return r=e,function(){return i(r)}}}))(),e._running--,e._tryToRun(),n()}}))()}schedule(e,...t){var n,r,i;return i=r=null,n=new this.Promise((function(e,t){return i=e,r=t})),this._queue.push({task:e,args:t,resolve:i,reject:r}),this._tryToRun(),n}};var Sync_1=Sync$1;const version="2.19.5";var version$1={version:version},version$2=Object.freeze({__proto__:null,version:version,default:version$1}),require$$0=Bottleneck_1,Events$2,Group,IORedisConnection,RedisConnection,Scripts,parser$2;function _slicedToArray$1(e,t){return _arrayWithHoles$1(e)||_iterableToArrayLimit$1(e,t)||_nonIterableRest$1()}function _nonIterableRest$1(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArrayLimit$1(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function _arrayWithHoles$1(e){if(Array.isArray(e))return e}function asyncGeneratorStep$1(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$1(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$1(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$1(s,r,i,o,a,"throw",e)}o(void 0)}))}}parser$2=parser$8,Events$2=Events_1,RedisConnection=RedisConnection_1,IORedisConnection=IORedisConnection_1,Scripts=Scripts$3,Group=function(){class e{constructor(e={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=e,parser$2.load(this.limiterOptions,this.defaults,this),this.Events=new Events$2(this),this.instances={},this.Bottleneck=require$$0,this._startAutoCleanup(),this.sharedConnection=null!=this.connection,null==this.connection&&("redis"===this.limiterOptions.datastore?this.connection=new RedisConnection(Object.assign({},this.limiterOptions,{Events:this.Events})):"ioredis"===this.limiterOptions.datastore&&(this.connection=new IORedisConnection(Object.assign({},this.limiterOptions,{Events:this.Events}))))}key(e=""){var t;return null!=(t=this.instances[e])?t:(()=>{var t;return t=this.instances[e]=new this.Bottleneck(Object.assign(this.limiterOptions,{id:`${this.id}-${e}`,timeout:this.timeout,connection:this.connection})),this.Events.trigger("created",t,e),t})()}deleteKey(e=""){var t=this;return _asyncToGenerator$1((function*(){var n,r;return r=t.instances[e],t.connection&&(n=yield t.connection.__runCommand__(["del",...Scripts.allKeys(`${t.id}-${e}`)])),null!=r&&(delete t.instances[e],yield r.disconnect()),null!=r||n>0}))()}limiters(){var e,t,n,r;for(e in n=[],t=this.instances)r=t[e],n.push({key:e,limiter:r});return n}keys(){return Object.keys(this.instances)}clusterKeys(){var e=this;return _asyncToGenerator$1((function*(){var t,n,r,i,s,o,a,c;if(null==e.connection)return e.Promise.resolve(e.keys());for(o=[],t=null,c=`b_${e.id}-`.length,n="_settings".length;0!==t;){var u=_slicedToArray$1(yield e.connection.__runCommand__(["scan",null!=t?t:0,"match",`b_${e.id}-*_settings`,"count",1e4]),2);for(t=~~u[0],i=0,a=(r=u[1]).length;i<a;i++)s=r[i],o.push(s.slice(c,-n))}return o}))()}_startAutoCleanup(){var e,t=this;return clearInterval(this.interval),"function"==typeof(e=this.interval=setInterval(_asyncToGenerator$1((function*(){var e,n,r,i,s,o;for(n in s=Date.now(),i=[],r=t.instances){o=r[n];try{(yield o._store.__groupCheck__(s))?i.push(t.deleteKey(n)):i.push(void 0)}catch(t){e=t,i.push(o.Events.trigger("error",e))}}return i})),this.timeout/2)).unref?e.unref():void 0}updateSettings(e={}){if(parser$2.overwrite(e,this.defaults,this),parser$2.overwrite(e,e,this.limiterOptions),null!=e.timeout)return this._startAutoCleanup()}disconnect(e=!0){var t;if(!this.sharedConnection)return null!=(t=this.connection)?t.disconnect(e):void 0}}return e.prototype.defaults={timeout:3e5,connection:null,Promise:Promise,id:"group-key"},e}.call(void 0);var Group_1=Group,Batcher,Events$1,parser$1;parser$1=parser$8,Events$1=Events_1,Batcher=function(){class e{constructor(e={}){this.options=e,parser$1.load(this.options,this.defaults,this),this.Events=new Events$1(this),this._arr=[],this._resetPromise(),this._lastFlush=Date.now()}_resetPromise(){return this._promise=new this.Promise(((e,t)=>this._resolve=e))}_flush(){return clearTimeout(this._timeout),this._lastFlush=Date.now(),this._resolve(),this.Events.trigger("batch",this._arr),this._arr=[],this._resetPromise()}add(e){var t;return this._arr.push(e),t=this._promise,this._arr.length===this.maxSize?this._flush():null!=this.maxTime&&1===this._arr.length&&(this._timeout=setTimeout((()=>this._flush()),this.maxTime)),t}}return e.prototype.defaults={maxTime:null,maxSize:null,Promise:Promise},e}.call(void 0);var Batcher_1=Batcher,require$$8=getCjsExportFromNamespace(version$2);function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_nonIterableRest()}function _iterableToArrayLimit(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function _toArray(e){return _arrayWithHoles(e)||_iterableToArray(e)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}function _arrayWithHoles(e){if(Array.isArray(e))return e}function asyncGeneratorStep(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep(s,r,i,o,a,"throw",e)}o(void 0)}))}}var Bottleneck,DEFAULT_PRIORITY,Events,Job,LocalDatastore,NUM_PRIORITIES,Queues,RedisDatastore,States,Sync,parser,splice=[].splice;NUM_PRIORITIES=10,DEFAULT_PRIORITY=5,parser=parser$8,Queues=Queues_1,Job=Job_1,LocalDatastore=LocalDatastore_1,RedisDatastore=RedisDatastore_1,Events=Events_1,States=States_1,Sync=Sync_1,Bottleneck=function(){class e{constructor(t={},...n){var r,i;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(t,n),parser.load(t,this.instanceDefaults,this),this._queues=new Queues(NUM_PRIORITIES),this._scheduled={},this._states=new States(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new Events(this),this._submitLock=new Sync("submit",this.Promise),this._registerLock=new Sync("register",this.Promise),i=parser.load(t,this.storeDefaults,{}),this._store=function(){if("redis"===this.datastore||"ioredis"===this.datastore||null!=this.connection)return r=parser.load(t,this.redisStoreDefaults,{}),new RedisDatastore(this,i,r);if("local"===this.datastore)return r=parser.load(t,this.localStoreDefaults,{}),new LocalDatastore(this,i,r);throw new e.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`)}.call(this),this._queues.on("leftzero",(()=>{var e;return null!=(e=this._store.heartbeat)&&"function"==typeof e.ref?e.ref():void 0})),this._queues.on("zero",(()=>{var e;return null!=(e=this._store.heartbeat)&&"function"==typeof e.unref?e.unref():void 0}))}_validateOptions(t,n){if(null==t||"object"!=typeof t||0!==n.length)throw new e.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.")}ready(){return this._store.ready}clients(){return this._store.clients}channel(){return`b_${this.id}`}channel_client(){return`b_${this.id}_${this._store.clientId}`}publish(e){return this._store.__publish__(e)}disconnect(e=!0){return this._store.__disconnect__(e)}chain(e){return this._limiter=e,this}queued(e){return this._queues.queued(e)}clusterQueued(){return this._store.__queued__()}empty(){return 0===this.queued()&&this._submitLock.isEmpty()}running(){return this._store.__running__()}done(){return this._store.__done__()}jobStatus(e){return this._states.jobStatus(e)}jobs(e){return this._states.statusJobs(e)}counts(){return this._states.statusCounts()}_randomIndex(){return Math.random().toString(36).slice(2)}check(e=1){return this._store.__check__(e)}_clearGlobalState(e){return null!=this._scheduled[e]&&(clearTimeout(this._scheduled[e].expiration),delete this._scheduled[e],!0)}_free(e,t,n,r){var i=this;return _asyncToGenerator((function*(){var t,s;try{if(s=(yield i._store.__free__(e,n.weight)).running,i.Events.trigger("debug",`Freed ${n.id}`,r),0===s&&i.empty())return i.Events.trigger("idle")}catch(e){return t=e,i.Events.trigger("error",t)}}))()}_run(e,t,n){var r,i,s;return t.doRun(),r=this._clearGlobalState.bind(this,e),s=this._run.bind(this,e,t),i=this._free.bind(this,e,t),this._scheduled[e]={timeout:setTimeout((()=>t.doExecute(this._limiter,r,s,i)),n),expiration:null!=t.options.expiration?setTimeout((function(){return t.doExpire(r,s,i)}),n+t.options.expiration):void 0,job:t}}_drainOne(e){return this._registerLock.schedule((()=>{var t,n,r,i,s;if(0===this.queued())return this.Promise.resolve(null);s=this._queues.getFirst();var o=r=s.first();return i=o.options,t=o.args,null!=e&&i.weight>e?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${i.id}`,{args:t,options:i}),n=this._randomIndex(),this._store.__register__(n,i.weight,i.expiration).then((({success:e,wait:o,reservoir:a})=>{var c;return this.Events.trigger("debug",`Drained ${i.id}`,{success:e,args:t,options:i}),e?(s.shift(),(c=this.empty())&&this.Events.trigger("empty"),0===a&&this.Events.trigger("depleted",c),this._run(n,r,o),this.Promise.resolve(i.weight)):this.Promise.resolve(null)})))}))}_drainAll(e,t=0){return this._drainOne(e).then((n=>{var r;return null!=n?(r=null!=e?e-n:e,this._drainAll(r,t+n)):this.Promise.resolve(t)})).catch((e=>this.Events.trigger("error",e)))}_dropAllQueued(e){return this._queues.shiftAll((function(t){return t.doDrop({message:e})}))}stop(t={}){var n,r;return t=parser.load(t,this.stopDefaults),r=e=>{var t;return t=()=>{var t;return(t=this._states.counts)[0]+t[1]+t[2]+t[3]===e},new this.Promise(((e,n)=>t()?e():this.on("done",(()=>{if(t())return this.removeAllListeners("done"),e()}))))},n=t.dropWaitingJobs?(this._run=function(e,n){return n.doDrop({message:t.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule((()=>this._submitLock.schedule((()=>{var e,n,i;for(e in n=this._scheduled)i=n[e],"RUNNING"===this.jobStatus(i.job.options.id)&&(clearTimeout(i.timeout),clearTimeout(i.expiration),i.job.doDrop({message:t.dropErrorMessage}));return this._dropAllQueued(t.dropErrorMessage),r(0)}))))):this.schedule({priority:NUM_PRIORITIES-1,weight:0},(()=>r(1))),this._receive=function(n){return n._reject(new e.prototype.BottleneckError(t.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new e.prototype.BottleneckError("stop() has already been called")),n}_addToQueue(t){var n=this;return _asyncToGenerator((function*(){var r,i,s,o,a,c,u;r=t.args,o=t.options;try{var l=yield n._store.__submit__(n.queued(),o.weight);a=l.reachedHWM,i=l.blocked,u=l.strategy}catch(e){return s=e,n.Events.trigger("debug",`Could not queue ${o.id}`,{args:r,options:o,error:s}),t.doDrop({error:s}),!1}return i?(t.doDrop(),!0):a&&(null!=(c=u===e.prototype.strategy.LEAK?n._queues.shiftLastFrom(o.priority):u===e.prototype.strategy.OVERFLOW_PRIORITY?n._queues.shiftLastFrom(o.priority+1):u===e.prototype.strategy.OVERFLOW?t:void 0)&&c.doDrop(),null==c||u===e.prototype.strategy.OVERFLOW)?(null==c&&t.doDrop(),a):(t.doQueue(a,i),n._queues.push(t),yield n._drainAll(),a)}))()}_receive(t){return null!=this._states.jobStatus(t.options.id)?(t._reject(new e.prototype.BottleneckError(`A job with the same id already exists (id=${t.options.id})`)),!1):(t.doReceive(),this._submitLock.schedule(this._addToQueue,t))}submit(...e){var t,n,r,i,s,o,a,c,u;"function"==typeof e[0]?(o=_toArray(e),n=o[0],e=o.slice(1),a=_slicedToArray(splice.call(e,-1),1),t=a[0],i=parser.load({},this.jobDefaults)):(i=(c=_toArray(e))[0],n=c[1],e=c.slice(2),u=_slicedToArray(splice.call(e,-1),1),t=u[0],i=parser.load(i,this.jobDefaults));return s=(...e)=>new this.Promise((function(t,r){return n(...e,(function(...e){return(null!=e[0]?r:t)(e)}))})),(r=new Job(s,e,i,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise)).promise.then((function(e){return"function"==typeof t?t(...e):void 0})).catch((function(e){return Array.isArray(e)?"function"==typeof t?t(...e):void 0:"function"==typeof t?t(e):void 0})),this._receive(r)}schedule(...e){var t,n,r;if("function"==typeof e[0]){var i=_toArray(e);r=i[0],e=i.slice(1),n={}}else{var s=_toArray(e);n=s[0],r=s[1],e=s.slice(2)}return t=new Job(r,e,n,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(t),t.promise}wrap(e){var t,n;return t=this.schedule.bind(this),(n=function(...n){return t(e.bind(this),...n)}).withOptions=function(n,...r){return t(n,e,...r)},n}updateSettings(e={}){var t=this;return _asyncToGenerator((function*(){return yield t._store.__updateSettings__(parser.overwrite(e,t.storeDefaults)),parser.overwrite(e,t.instanceDefaults,t),t}))()}currentReservoir(){return this._store.__currentReservoir__()}incrementReservoir(e=0){return this._store.__incrementReservoir__(e)}}return e.default=e,e.Events=Events,e.version=e.prototype.version=require$$8.version,e.strategy=e.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},e.BottleneckError=e.prototype.BottleneckError=BottleneckError_1,e.Group=e.prototype.Group=Group_1,e.RedisConnection=e.prototype.RedisConnection=RedisConnection_1,e.IORedisConnection=e.prototype.IORedisConnection=IORedisConnection_1,e.Batcher=e.prototype.Batcher=Batcher_1,e.prototype.jobDefaults={priority:DEFAULT_PRIORITY,weight:1,expiration:null,id:"<no-id>"},e.prototype.storeDefaults={maxConcurrent:null,minTime:0,highWater:null,strategy:e.prototype.strategy.LEAK,penalty:null,reservoir:null,reservoirRefreshInterval:null,reservoirRefreshAmount:null,reservoirIncreaseInterval:null,reservoirIncreaseAmount:null,reservoirIncreaseMaximum:null},e.prototype.localStoreDefaults={Promise:Promise,timeout:null,heartbeatInterval:250},e.prototype.redisStoreDefaults={Promise:Promise,timeout:null,heartbeatInterval:5e3,clientTimeout:1e4,Redis:null,clientOptions:{},clusterNodes:null,clearDatastore:!1,connection:null},e.prototype.instanceDefaults={datastore:"local",connection:null,id:"<no-id>",rejectOnDrop:!0,trackDoneStatus:!1,Promise:Promise},e.prototype.stopDefaults={enqueueErrorMessage:"This limiter has been stopped and cannot accept new jobs.",dropWaitingJobs:!0,dropErrorMessage:"This limiter has been stopped."},e}.call(void 0);var Bottleneck_1=Bottleneck,lib=require$$0,browser="object"==typeof self?self.FormData:window.FormData;const GRANT_TYPE$1="client_credentials",castClientOptionsToRequestParams=e=>{const{scope:t,clientId:n,clientSecret:r}=e;if(!n)throw new Error('Missing required "clientId" parameter to perform client credentials grant');if(!r)throw new Error('Missing required "clientSecret" parameter to perform client credentials grant');return Object.assign({client_id:n,client_secret:r,grant_type:GRANT_TYPE$1},t?{scope:t}:{})},isEligible$1=e=>{try{return!!castClientOptionsToRequestParams(e)}catch(e){return!1}},requestToken$1=(e,t)=>e(castClientOptionsToRequestParams(t)),RESPONSE_TYPE="token",castToAuthorizationRequestParams=e=>{const{clientId:t,scope:n,state:r,redirectUri:i}=e;if(!t)throw new Error('Missing required "clientId" parameter to perform implicit grant');return Object.assign(Object.assign({client_id:t,redirect_uri:i||window.location.href,response_type:RESPONSE_TYPE},n?{scope:n}:{}),r?{state:r}:{})},isEligibleForClientRedirect=e=>{try{return!!castToAuthorizationRequestParams(e)}catch(e){return!1}},getRedirectUrl=e=>`${e.oauthUrl}/oauth/authorize?${queryString.stringify(castToAuthorizationRequestParams(e),{skipNull:!0,skipEmptyString:!0})}`,GRANT_TYPE="password",castToTokenRequestParams=e=>{const{username:t,password:n,scope:r,clientId:i,clientSecret:s}=e;if(!i)throw new Error('Missing required "clientId" parameter to perform password grant');if(!t)throw new Error('Missing required "username" parameter to perform password grant');if(!n)throw new Error('Missing required "password" parameter to perform password grant');return Object.assign(Object.assign({client_id:i,grant_type:GRANT_TYPE,password:n,username:t},r?{scope:r}:{}),s?{client_secret:s}:{})},isEligible=e=>{try{return!!castToTokenRequestParams(e)}catch(e){return!1}},requestToken=(e,t)=>e(castToTokenRequestParams(t));async function maybeUpdateToken(e,t,n,r=!1){if(!r&&e.get("accessToken"))return;const i=Object.assign(Object.assign({},n),{refreshToken:e.get("refreshToken")});if(isEligible$2(i))return e.set(await requestToken$2(t,i));if(isEligible(n))return e.set(await requestToken(t,n));if("undefined"!=typeof window&&n.implicit){const t=queryString.parse(window.location.hash),r=t&&t.access_token;if(r)return window.history.replaceState({},"",window.location.href.split("#")[0]),e.set({accessToken:r});if(isEligibleForClientRedirect(n))return void(window.location.href=getRedirectUrl(n))}return!r&&isEligible$3(n)?e.set(await requestToken$3(t,n)):n.authorizationRedirect&&isEligibleForClientRedirect$1(n)?n.authorizationRedirect(getRedirectUrl$1(n)):isEligible$1(n)?e.set(await requestToken$1(t,n)):void 0}function sleep(e){return new Promise((t=>setTimeout((()=>t(!0)),e)))}const requestLogger=makeLogger("REST API Request"),responseLogger=makeLogger("REST API Response"),RETRYABLE_STATUS_CODES=[401,408,429,502,503,504],TOKEN_REFRESH_STATUS_CODES=[401],queue=new lib({maxConcurrent:QUEUE_CONCURRENCY,minTime:QUEUE_DELAY,reservoir:QUEUE_RESERVOIR}),refillIntervalSet=new Set;function isFormData(e){return void 0!==e&&void 0!==e.formData}function refillReservoir(){if(0===refillIntervalSet.size){const e=setInterval((async()=>{const t=await queue.currentReservoir();return queue.empty()&&0===await queue.running()&&t>10?await queue.incrementReservoir(1)&&fnClearInterval(e)&&refillIntervalSet.delete(e):t<QUEUE_RESERVOIR?queue.incrementReservoir(1):fnClearInterval(e)&&refillIntervalSet.delete(e)}),QUEUE_RESERVOIR_REFILL_INTERVAL);return refillIntervalSet.add(e)}return refillIntervalSet}async function makeResultFromResponse(e){return RETRYABLE_STATUS_CODES.includes(e.status)?e.clone():e.ok?"application/json"!==e.headers.get("content-type")&&204!==e.status?new Error(`Response content type was "${e.headers.get("content-type")}" but expected JSON`):{body:204===e.status?"":await e.json(),status:e.status}:new Error(`${e.status} ${e.statusText}\n\n${await e.text()}`)}function responseWasSuccessful(e){return!RETRYABLE_STATUS_CODES.includes(e.status)}function makeApiRequest(e,t,n,r,i,s,o){return async(a,c)=>{if(c>0){if(c>n.requestMaxRetries){const e=`Maximum number of retries reached while retrying ${a.method} request ${a.path}.`;throw requestLogger.error(e),new Error(e)}requestLogger.warn(`Warning: encountered ${a.status}. Retrying ${a.method} request ${a.path} (retry #${c}).`),await sleep(Math.ceil(Math.random()*n.requestBackOffInterval*2**c))}if(await maybeUpdateToken(e,t,n,c>0&&TOKEN_REFRESH_STATUS_CODES.includes(a.status)),!e.get("accessToken"))throw new Error("Unable to get OAuth2 access token.");try{return refillReservoir()&&await queue.schedule((async()=>{const t=r.toUpperCase(),a=s&&s.query?(i.includes("?")?"&":"?")+queryString.stringify(s.query,{skipNull:!0,skipEmptyString:!0}):"",c=`${n.apiUrl}/api${i}${a}`,u=s&&s.body,l=isFormData(u),d=isFormData(u)?u.formData:{},p=Object.entries(d).reduce(((e,[t,n])=>(e.append.apply(e,[t].concat(n)),e)),new browser),h=Object.assign(Object.assign(Object.assign(Object.assign({accept:"application/json",authorization:`Bearer ${e.get("accessToken")}`},l?{}:{"content-type":"application/json"}),"undefined"==typeof window&&"undefined"==typeof document&&{"user-agent":USER_AGENT}),s&&s.headers?s.headers:{}),l&&p.getHeaders?p.getHeaders():{});[].DEBUG&&console.log({sdkLogs:{method:t,url:c}}),requestLogger.log(t,c,{body:u,headers:h});const m={body:l?p:JSON.stringify(u)},y=await fetch(c,Object.assign({cache:"no-cache",credentials:"omit",headers:h,method:t,mode:"cors"},l||u?m:{})),_=await makeResultFromResponse(y);return responseLogger.log(t,c,_ instanceof Error?{error:_}:{body:_.body,status:y.status}),_ instanceof Error&&o?{body:_.message,status:y.status}:_}))}catch(e){return e}}}async function request(e,t,n,r,i,s,o){const a=await until(responseWasSuccessful,makeApiRequest(e,t,n,r,i,s,o));if(a instanceof Error)throw requestLogger.log("Request Error",a,s),a;return o?a:a.body}const API_METHODS=[agentCreate,agentCreatePermissions,activeUnitsGetByAppId,appCreate,appGetById,bucketCreate,bucketAddFile,bucketRemoveFile,bucketRemoveFilesInPath,bucketGet,conversationGetById,conversationCreateMessage,fileCreate,fileDelete,notificationSettingsResetByUser,notificationSettingsUpdateByUser,groupCreate,groupGetById,groupUpdateById,getGroups,lookupIds,notificationsGetByUser,notificationUpdateRead,notificationsUpdateReadByUser,propertyCreate,propertyGetById,propertyUpdateById,getProperties,serviceProviderCreate,serviceProviderGetById,serviceProviderUpdateById,registrationCodeCreate,registrationCodeUpdateById,registrationCodeDelete,registrationCodeGetById,ticketCreateOnUser,ticketCreateOnServiceProvider,ticketGetById,unitCreate,unitGetById,unitUpdateById,getUnits,userCreate,userGetById,userUpdateById,userChangePassword,userCreatePermission,userCreatePermissionBatch,userGetPermissions,userDeletePermission,userCheckInToUtilisationPeriod,userGetUtilisationPeriods,userGetByEmail,getCurrentUser,getUsers,userRelationCreate,userRelationDelete,userRelationsGetByUser,utilisationPeriodCreate,utilisationPeriodDelete,utilisationPeriodGetById,utilisationPeriodUpdateById,utilisationPeriodCheckInUser,utilisationPeriodCheckOutUser,utilisationPeriodAddRegistrationCode,bookingUpdateById,bookingGetById];function restClient(e=DEFAULT_API_WRAPPER_OPTIONS){const t=Object.assign(Object.assign({},DEFAULT_API_WRAPPER_OPTIONS),e);if(void 0===t.apiUrl)throw new Error("API URL is undefined.");if(void 0===t.oauthUrl)throw new Error("OAuth2 URL is undefined.");if(!t.clientId&&!t.accessToken&&!t.tokenStore&&"undefined"==typeof window)throw new Error('Missing required "clientId" or "accessToken" parameter .');const n=makeFetchTokenRequester(`${t.oauthUrl}/oauth/token`),r=t.tokenStore||createTokenStore({accessToken:t.accessToken,refreshToken:t.refreshToken}),i=partial(request,r,n,t),s=partial(del,i),o=partial(get,i),a=partial(post,i),c=partial(patch,i),u=partial(put,i),l={authorizationCode:{getUri:(e=t.state||pseudoRandomString())=>partial(getRedirectUrl$1,Object.assign(Object.assign({},t),{state:e}))(),requestToken:e=>requestAndSaveToStore(partial(requestToken$3,n,Object.assign(Object.assign({},t),{authorizationCode:e||t.authorizationCode})),r)},generateState:pseudoRandomString,refreshToken:e=>requestAndSaveToStore(partial(requestToken$2,n,Object.assign(Object.assign({},t),{refreshToken:e||r.get("refreshToken")})),r)},d=API_METHODS.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:(...e)=>t(d,...e)})),{delete:s,get:o,oauth:l,options:t,patch:c,post:a,put:u});return d}var EnumResource,EnumCountryCode,EnumLocale,EnumTimezone,EnumServiceProviderType,EnumCommunicationMethodType,EnumInputChannel,EnumLookupUserType;exports.EnumResource=void 0,EnumResource=exports.EnumResource||(exports.EnumResource={}),EnumResource.group="group",EnumResource.property="property",EnumResource.serviceProvider="propertyManager",EnumResource.registrationCode="registrationCode",EnumResource.unit="unit",EnumResource.user="user",EnumResource.utilisationPeriod="utilisationPeriod",exports.EnumCountryCode=void 0,EnumCountryCode=exports.EnumCountryCode||(exports.EnumCountryCode={}),EnumCountryCode.CH="CH",EnumCountryCode.DE="DE",EnumCountryCode.FR="FR",EnumCountryCode.IT="IT",EnumCountryCode.NL="NL",EnumCountryCode.PT="PT",EnumCountryCode.US="US",exports.EnumLocale=void 0,EnumLocale=exports.EnumLocale||(exports.EnumLocale={}),EnumLocale.ch_de="ch_DE",EnumLocale.ch_fr="ch_FR",EnumLocale.ch_it="ch_it",EnumLocale.de_DE="de_DE",EnumLocale.it_IT="it_IT",EnumLocale.fr_FR="fr_FR",EnumLocale.pt_PT="pt_PT",EnumLocale.en_US="en_US",exports.EnumTimezone=void 0,EnumTimezone=exports.EnumTimezone||(exports.EnumTimezone={}),EnumTimezone.EuropeBerlin="Europe/Berlin",EnumTimezone.EuropeLondon="Europe/London",EnumTimezone.EuropeSofia="Europe/Sofia",EnumTimezone.EuropeZurich="Europe/Zurich",EnumTimezone.UTC="UTC",exports.EnumServiceProviderType=void 0,EnumServiceProviderType=exports.EnumServiceProviderType||(exports.EnumServiceProviderType={}),EnumServiceProviderType.propertyManager="property-manager",EnumServiceProviderType.craftspeople="craftspeople",exports.EnumCommunicationMethodType=void 0,EnumCommunicationMethodType=exports.EnumCommunicationMethodType||(exports.EnumCommunicationMethodType={}),EnumCommunicationMethodType.email="email",exports.EnumInputChannel=void 0,EnumInputChannel=exports.EnumInputChannel||(exports.EnumInputChannel={}),EnumInputChannel.APP="app",EnumInputChannel.COCKPIT="cockpit",EnumInputChannel.CRAFTSMEN="craftsmen",EnumInputChannel.EMAIL="email",EnumInputChannel.PHONE="phone",EnumInputChannel.WHATS_APP="whats_app",exports.EnumLookupUserType=void 0,EnumLookupUserType=exports.EnumLookupUserType||(exports.EnumLookupUserType={}),EnumLookupUserType.agent="agent",EnumLookupUserType.tenant="tenant",exports.createTokenStore=createTokenStore,exports.restClient=restClient,Object.defineProperty(exports,"__esModule",{value:!0})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).allthings={})}(this,(function(exports){"use strict";const version$3="5.0.4",REST_API_URL="https://api.allthings.me",OAUTH_URL="https://accounts.allthings.me",QUEUE_CONCURRENCY=void 0,QUEUE_DELAY=0,QUEUE_RESERVOIR=30,QUEUE_RESERVOIR_REFILL_INTERVAL=166,REQUEST_BACK_OFF_INTERVAL=200,REQUEST_MAX_RETRIES=50,DEFAULT_API_WRAPPER_OPTIONS={apiUrl:[].ALLTHINGS_REST_API_URL||REST_API_URL,clientId:[].ALLTHINGS_OAUTH_CLIENT_ID,clientSecret:[].ALLTHINGS_OAUTH_CLIENT_SECRET,oauthUrl:[].ALLTHINGS_OAUTH_URL||OAUTH_URL,password:[].ALLTHINGS_OAUTH_PASSWORD,requestBackOffInterval:REQUEST_BACK_OFF_INTERVAL,requestMaxRetries:REQUEST_MAX_RETRIES,scope:"user:profile",username:[].ALLTHINGS_OAUTH_USERNAME},USER_AGENT=`Allthings Node SDK REST Client/${version$3}`;var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function unwrapExports(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function createCommonjsModule(e,t){return e(t={exports:{}},t.exports),t.exports}function getCjsExportFromNamespace(e){return e&&e.default||e}var strictUriEncode=e=>encodeURIComponent(e).replace(/[!'()*]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),token="%[a-f0-9]{2}",singleMatcher=new RegExp("("+token+")|([^%]+?)","gi"),multiMatcher=new RegExp("("+token+")+","gi");function decodeComponents(e,t){try{return[decodeURIComponent(e.join(""))]}catch(e){}if(1===e.length)return e;t=t||1;var n=e.slice(0,t),r=e.slice(t);return Array.prototype.concat.call([],decodeComponents(n),decodeComponents(r))}function decode(e){try{return decodeURIComponent(e)}catch(r){for(var t=e.match(singleMatcher)||[],n=1;n<t.length;n++)t=(e=decodeComponents(t,n).join("")).match(singleMatcher)||[];return e}}function customDecodeURIComponent(e){for(var t={"%FE%FF":"��","%FF%FE":"��"},n=multiMatcher.exec(e);n;){try{t[n[0]]=decodeURIComponent(n[0])}catch(e){var r=decode(n[0]);r!==n[0]&&(t[n[0]]=r)}n=multiMatcher.exec(e)}t["%C2"]="�";for(var i=Object.keys(t),s=0;s<i.length;s++){var o=i[s];e=e.replace(new RegExp(o,"g"),t[o])}return e}var decodeUriComponent=function(e){if("string"!=typeof e)throw new TypeError("Expected `encodedURI` to be of type `string`, got `"+typeof e+"`");try{return e=e.replace(/\+/g," "),decodeURIComponent(e)}catch(t){return customDecodeURIComponent(e)}},splitOnFirst=(e,t)=>{if("string"!=typeof e||"string"!=typeof t)throw new TypeError("Expected the arguments to be of type `string`");if(""===t)return[e];const n=e.indexOf(t);return-1===n?[e]:[e.slice(0,n),e.slice(n+t.length)]},filterObj=function(e,t){for(var n={},r=Object.keys(e),i=Array.isArray(t),s=0;s<r.length;s++){var o=r[s],a=e[o];(i?-1!==t.indexOf(o):t(o,a,e))&&(n[o]=a)}return n},queryString=createCommonjsModule((function(e,t){const n=Symbol("encodeFragmentIdentifier");function r(e){if("string"!=typeof e||1!==e.length)throw new TypeError("arrayFormatSeparator must be single character string")}function i(e,t){return t.encode?t.strict?strictUriEncode(e):encodeURIComponent(e):e}function s(e,t){return t.decode?decodeUriComponent(e):e}function o(e){return Array.isArray(e)?e.sort():"object"==typeof e?o(Object.keys(e)).sort(((e,t)=>Number(e)-Number(t))).map((t=>e[t])):e}function a(e){const t=e.indexOf("#");return-1!==t&&(e=e.slice(0,t)),e}function c(e){const t=(e=a(e)).indexOf("?");return-1===t?"":e.slice(t+1)}function u(e,t){return t.parseNumbers&&!Number.isNaN(Number(e))&&"string"==typeof e&&""!==e.trim()?e=Number(e):!t.parseBooleans||null===e||"true"!==e.toLowerCase()&&"false"!==e.toLowerCase()||(e="true"===e.toLowerCase()),e}function l(e,t){r((t=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},t)).arrayFormatSeparator);const n=function(e){let t;switch(e.arrayFormat){case"index":return(e,n,r)=>{t=/\[(\d*)\]$/.exec(e),e=e.replace(/\[\d*\]$/,""),t?(void 0===r[e]&&(r[e]={}),r[e][t[1]]=n):r[e]=n};case"bracket":return(e,n,r)=>{t=/(\[\])$/.exec(e),e=e.replace(/\[\]$/,""),t?void 0!==r[e]?r[e]=[].concat(r[e],n):r[e]=[n]:r[e]=n};case"colon-list-separator":return(e,n,r)=>{t=/(:list)$/.exec(e),e=e.replace(/:list$/,""),t?void 0!==r[e]?r[e]=[].concat(r[e],n):r[e]=[n]:r[e]=n};case"comma":case"separator":return(t,n,r)=>{const i="string"==typeof n&&n.includes(e.arrayFormatSeparator),o="string"==typeof n&&!i&&s(n,e).includes(e.arrayFormatSeparator);n=o?s(n,e):n;const a=i||o?n.split(e.arrayFormatSeparator).map((t=>s(t,e))):null===n?n:s(n,e);r[t]=a};case"bracket-separator":return(t,n,r)=>{const i=/(\[\])$/.test(t);if(t=t.replace(/\[\]$/,""),!i)return void(r[t]=n?s(n,e):n);const o=null===n?[]:n.split(e.arrayFormatSeparator).map((t=>s(t,e)));void 0!==r[t]?r[t]=[].concat(r[t],o):r[t]=o};default:return(e,t,n)=>{void 0!==n[e]?n[e]=[].concat(n[e],t):n[e]=t}}}(t),i=Object.create(null);if("string"!=typeof e)return i;if(!(e=e.trim().replace(/^[?#&]/,"")))return i;for(const r of e.split("&")){if(""===r)continue;let[e,o]=splitOnFirst(t.decode?r.replace(/\+/g," "):r,"=");o=void 0===o?null:["comma","separator","bracket-separator"].includes(t.arrayFormat)?o:s(o,t),n(s(e,t),o,i)}for(const e of Object.keys(i)){const n=i[e];if("object"==typeof n&&null!==n)for(const e of Object.keys(n))n[e]=u(n[e],t);else i[e]=u(n,t)}return!1===t.sort?i:(!0===t.sort?Object.keys(i).sort():Object.keys(i).sort(t.sort)).reduce(((e,t)=>{const n=i[t];return Boolean(n)&&"object"==typeof n&&!Array.isArray(n)?e[t]=o(n):e[t]=n,e}),Object.create(null))}t.extract=c,t.parse=l,t.stringify=(e,t)=>{if(!e)return"";r((t=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},t)).arrayFormatSeparator);const n=n=>t.skipNull&&null==e[n]||t.skipEmptyString&&""===e[n],s=function(e){switch(e.arrayFormat){case"index":return t=>(n,r)=>{const s=n.length;return void 0===r||e.skipNull&&null===r||e.skipEmptyString&&""===r?n:null===r?[...n,[i(t,e),"[",s,"]"].join("")]:[...n,[i(t,e),"[",i(s,e),"]=",i(r,e)].join("")]};case"bracket":return t=>(n,r)=>void 0===r||e.skipNull&&null===r||e.skipEmptyString&&""===r?n:null===r?[...n,[i(t,e),"[]"].join("")]:[...n,[i(t,e),"[]=",i(r,e)].join("")];case"colon-list-separator":return t=>(n,r)=>void 0===r||e.skipNull&&null===r||e.skipEmptyString&&""===r?n:null===r?[...n,[i(t,e),":list="].join("")]:[...n,[i(t,e),":list=",i(r,e)].join("")];case"comma":case"separator":case"bracket-separator":{const t="bracket-separator"===e.arrayFormat?"[]=":"=";return n=>(r,s)=>void 0===s||e.skipNull&&null===s||e.skipEmptyString&&""===s?r:(s=null===s?"":s,0===r.length?[[i(n,e),t,i(s,e)].join("")]:[[r,i(s,e)].join(e.arrayFormatSeparator)])}default:return t=>(n,r)=>void 0===r||e.skipNull&&null===r||e.skipEmptyString&&""===r?n:null===r?[...n,i(t,e)]:[...n,[i(t,e),"=",i(r,e)].join("")]}}(t),o={};for(const t of Object.keys(e))n(t)||(o[t]=e[t]);const a=Object.keys(o);return!1!==t.sort&&a.sort(t.sort),a.map((n=>{const r=e[n];return void 0===r?"":null===r?i(n,t):Array.isArray(r)?0===r.length&&"bracket-separator"===t.arrayFormat?i(n,t)+"[]":r.reduce(s(n),[]).join("&"):i(n,t)+"="+i(r,t)})).filter((e=>e.length>0)).join("&")},t.parseUrl=(e,t)=>{t=Object.assign({decode:!0},t);const[n,r]=splitOnFirst(e,"#");return Object.assign({url:n.split("?")[0]||"",query:l(c(e),t)},t&&t.parseFragmentIdentifier&&r?{fragmentIdentifier:s(r,t)}:{})},t.stringifyUrl=(e,r)=>{r=Object.assign({encode:!0,strict:!0,[n]:!0},r);const s=a(e.url).split("?")[0]||"",o=t.extract(e.url),c=t.parse(o,{sort:!1}),u=Object.assign(c,e.query);let l=t.stringify(u,r);l&&(l=`?${l}`);let d=function(e){let t="";const n=e.indexOf("#");return-1!==n&&(t=e.slice(n)),t}(e.url);return e.fragmentIdentifier&&(d=`#${r[n]?i(e.fragmentIdentifier,r):e.fragmentIdentifier}`),`${s}${l}${d}`},t.pick=(e,r,i)=>{i=Object.assign({parseFragmentIdentifier:!0,[n]:!1},i);const{url:s,query:o,fragmentIdentifier:a}=t.parseUrl(e,i);return t.stringifyUrl({url:s,query:filterObj(o,r),fragmentIdentifier:a},i)},t.exclude=(e,n,r)=>{const i=Array.isArray(n)?e=>!n.includes(e):(e,t)=>!n(e,t);return t.pick(e,i,r)}}));queryString.extract,queryString.parse,queryString.stringify,queryString.parseUrl,queryString.stringifyUrl,queryString.pick,queryString.exclude;const RESPONSE_TYPE$1="code",GRANT_TYPE$3="authorization_code",castToAuthorizationRequestParams$1=e=>{const{redirectUri:t,clientId:n,scope:r,state:i}=e;if(!n)throw new Error('Missing required "clientId" parameter to perform authorization code grant redirect');if(!t)throw new Error('Missing required "redirectUri" parameter to perform authorization code grant redirect');return Object.assign(Object.assign({client_id:n,redirect_uri:t,response_type:RESPONSE_TYPE$1},r?{scope:r}:{}),i?{state:i}:{})},isEligibleForClientRedirect$1=e=>{try{return!!castToAuthorizationRequestParams$1(e)}catch(e){return!1}},getRedirectUrl$1=e=>`${e.oauthUrl}/oauth/authorize?${queryString.stringify(castToAuthorizationRequestParams$1(e),{skipNull:!0,skipEmptyString:!0})}`,castToTokenRequestParams$2=e=>{const{authorizationCode:t,redirectUri:n,clientId:r,clientSecret:i}=e;if(!r)throw new Error('Missing required "clientId" parameter to perform authorization code grant');if(!n)throw new Error('Missing required "redirectUri" parameter to perform authorization code grant');if(!t)throw new Error('Missing required "authorizationCode" parameter to perform authorization code grant');return Object.assign({client_id:r,code:t,grant_type:GRANT_TYPE$3,redirect_uri:n},i?{client_secret:i}:{})},isEligible$3=e=>{try{return!!castToTokenRequestParams$2(e)}catch(e){return!1}},requestToken$3=(e,t)=>e(castToTokenRequestParams$2(t));function createTokenStore(e){const t=new Map(Object.entries(e||{}));return{get:e=>t.get(e),reset:()=>t.clear(),set:e=>Object.entries(e).forEach((([e,n])=>t.set(e,n)))}}var browserPonyfill=createCommonjsModule((function(e,t){var n="undefined"!=typeof self?self:commonjsGlobal,r=function(){function e(){this.fetch=!1,this.DOMException=n.DOMException}return e.prototype=n,new e}();!function(e){!function(t){var n="URLSearchParams"in e,r="Symbol"in e&&"iterator"in Symbol,i="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),s="FormData"in e,o="ArrayBuffer"in e;if(o)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(e){return e&&a.indexOf(Object.prototype.toString.call(e))>-1};function u(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function l(e){return"string"!=typeof e&&(e=String(e)),e}function d(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return r&&(t[Symbol.iterator]=function(){return t}),t}function p(e){this.map={},e instanceof p?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function h(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function m(e){return new Promise((function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}}))}function y(e){var t=new FileReader,n=m(t);return t.readAsArrayBuffer(e),n}function _(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function f(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:i&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:s&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:n&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():o&&i&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=_(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):o&&(ArrayBuffer.prototype.isPrototypeOf(e)||c(e))?this._bodyArrayBuffer=_(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):n&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var e=h(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?h(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(y)}),this.text=function(){var e,t,n,r=h(this);if(r)return r;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,n=m(t),t.readAsText(e),n;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),n=new Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},s&&(this.formData=function(){return this.text().then(b)}),this.json=function(){return this.text().then(JSON.parse)},this}p.prototype.append=function(e,t){e=u(e),t=l(t);var n=this.map[e];this.map[e]=n?n+", "+t:t},p.prototype.delete=function(e){delete this.map[u(e)]},p.prototype.get=function(e){return e=u(e),this.has(e)?this.map[e]:null},p.prototype.has=function(e){return this.map.hasOwnProperty(u(e))},p.prototype.set=function(e,t){this.map[u(e)]=l(t)},p.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},p.prototype.keys=function(){var e=[];return this.forEach((function(t,n){e.push(n)})),d(e)},p.prototype.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),d(e)},p.prototype.entries=function(){var e=[];return this.forEach((function(t,n){e.push([n,t])})),d(e)},r&&(p.prototype[Symbol.iterator]=p.prototype.entries);var g=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function v(e,t){var n,r,i=(t=t||{}).body;if(e instanceof v){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new p(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,i||null==e._bodyInit||(i=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new p(t.headers)),this.method=(n=t.method||this.method||"GET",r=n.toUpperCase(),g.indexOf(r)>-1?r:n),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function b(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var n=e.split("="),r=n.shift().replace(/\+/g," "),i=n.join("=").replace(/\+/g," ");t.append(decodeURIComponent(r),decodeURIComponent(i))}})),t}function E(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new p(t.headers),this.url=t.url||"",this._initBody(e)}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})},f.call(v.prototype),f.call(E.prototype),E.prototype.clone=function(){return new E(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},E.error=function(){var e=new E(null,{status:0,statusText:""});return e.type="error",e};var T=[301,302,303,307,308];E.redirect=function(e,t){if(-1===T.indexOf(t))throw new RangeError("Invalid status code");return new E(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function k(e,n){return new Promise((function(r,s){var o=new v(e,n);if(o.signal&&o.signal.aborted)return s(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function c(){a.abort()}a.onload=function(){var e,t,n={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new p,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var n=e.split(":"),r=n.shift().trim();if(r){var i=n.join(":").trim();t.append(r,i)}})),t)};n.url="responseURL"in a?a.responseURL:n.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;r(new E(i,n))},a.onerror=function(){s(new TypeError("Network request failed"))},a.ontimeout=function(){s(new TypeError("Network request failed"))},a.onabort=function(){s(new t.DOMException("Aborted","AbortError"))},a.open(o.method,o.url,!0),"include"===o.credentials?a.withCredentials=!0:"omit"===o.credentials&&(a.withCredentials=!1),"responseType"in a&&i&&(a.responseType="blob"),o.headers.forEach((function(e,t){a.setRequestHeader(t,e)})),o.signal&&(o.signal.addEventListener("abort",c),a.onreadystatechange=function(){4===a.readyState&&o.signal.removeEventListener("abort",c)}),a.send(void 0===o._bodyInit?null:o._bodyInit)}))}k.polyfill=!0,e.fetch||(e.fetch=k,e.Headers=p,e.Request=v,e.Response=E),t.Headers=p,t.Request=v,t.Response=E,t.fetch=k,Object.defineProperty(t,"__esModule",{value:!0})}({})}(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=r;(t=i.fetch).default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t})),fetch=unwrapExports(browserPonyfill);browserPonyfill.fetch,browserPonyfill.Headers,browserPonyfill.Request,browserPonyfill.Response;const SUBSCRIPTIONS=[].DEBUG&&[].DEBUG.split(",").map((e=>e.trim()))||[];function makeLogger(e){return["log","info","warn","error"].reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:function(...t){return(SUBSCRIPTIONS.includes("*")||SUBSCRIPTIONS.includes(e)||SUBSCRIPTIONS.includes(e.toLocaleLowerCase()))&&console[n](`${e}:`,...t),!0}})),{})}const logger=makeLogger("OAuth Token Request"),makeFetchTokenRequester=e=>async t=>{try{const n=await fetch(e,{body:queryString.stringify(t,{skipNull:!0,skipEmptyString:!0}),cache:"no-cache",credentials:"omit",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":USER_AGENT},method:"POST",mode:"cors"});if(200!==n.status)throw n;const{access_token:r,refresh_token:i,expires_in:s}=await n.json();return{accessToken:r,expiresIn:s,refreshToken:i}}catch(e){if(!e.status)throw e;const t=`HTTP ${e.status} — ${e.statusText}`;throw logger.error(t,e.response),new Error(`HTTP ${e.status} — ${e.statusText}. Could not get token.`)}},GRANT_TYPE$2="refresh_token",castToTokenRequestParams$1=e=>{const{clientId:t,clientSecret:n,refreshToken:r,scope:i}=e;if(!t)throw new Error('Missing required "clientId" parameter to perform refresh token grant');if(!r)throw new Error('Missing required "refreshToken" parameter to perform refresh token grant');return Object.assign(Object.assign({client_id:t,grant_type:GRANT_TYPE$2,refresh_token:r},n?{client_secret:n}:{}),i?{scope:i}:{})},isEligible$2=e=>{try{return!!castToTokenRequestParams$1(e)}catch(e){return!1}},requestToken$2=(e,t)=>e(castToTokenRequestParams$1(t));async function requestAndSaveToStore(e,t){const n=await e();return t.set(n),n}const partial=(e,...t)=>(...n)=>e(...t,...n);async function until(e,t,n,r=0){const i=await t(n,r);return await e(i,r)?i:until(e,t,i,r+1)}function fnClearInterval(e){return clearInterval(e),!0}function pseudoRandomString(e=16){let t="";for(;t.length<e;)t+=Math.random().toString(36).substr(2);return t.substr(0,e)}async function del(e,t,n,r){return e("delete",t,{body:n},r)}async function get(e,t,n,r){return e("get",t,{query:n},r)}var __rest$4=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n},EnumGender,EnumUserType,EnumCommunicationPreferenceChannel,EnumUserPermissionRole,EnumUserPermissionObjectType;!function(e){e.female="female",e.male="male"}(EnumGender||(EnumGender={})),function(e){e.allthingsUser="allthings_user",e.allthingsContent="allthings_content",e.customer="customer",e.demoContent="demo_content",e.demoPublic="demo_public",e.partner="partner"}(EnumUserType||(EnumUserType={})),exports.EnumCommunicationPreferenceChannel=void 0,EnumCommunicationPreferenceChannel=exports.EnumCommunicationPreferenceChannel||(exports.EnumCommunicationPreferenceChannel={}),EnumCommunicationPreferenceChannel.push="push",EnumCommunicationPreferenceChannel.email="email",exports.EnumUserPermissionRole=void 0,EnumUserPermissionRole=exports.EnumUserPermissionRole||(exports.EnumUserPermissionRole={}),EnumUserPermissionRole.appAdmin="app-admin",EnumUserPermissionRole.appOwner="app-owner",EnumUserPermissionRole.articlesAgent="articles-agent",EnumUserPermissionRole.articlesViewOnly="articles-view-only",EnumUserPermissionRole.bookableAssetAgent="bookable-asset-agent",EnumUserPermissionRole.bookingAgent="booking-agent",EnumUserPermissionRole.cockpitManager="cockpit-manager",EnumUserPermissionRole.dataConnectorAdmin="data-connector-admin",EnumUserPermissionRole.documentAdmin="doc-admin",EnumUserPermissionRole.externalAgent="external-agent",EnumUserPermissionRole.globalOrgAdmin="global-org-admin",EnumUserPermissionRole.globalUserAdmin="global-user-admin",EnumUserPermissionRole.orgAdmin="org-admin",EnumUserPermissionRole.orgTeamManager="org-team-manager",EnumUserPermissionRole.pinboardAgent="pinboard-agent",EnumUserPermissionRole.platformOwner="platform-owner",EnumUserPermissionRole.qa="qa",EnumUserPermissionRole.serviceCenterAgent="service-center-agent",EnumUserPermissionRole.serviceCenterManager="service-center-manager",EnumUserPermissionRole.setup="setup",EnumUserPermissionRole.tenantManager="tenant-manager",exports.EnumUserPermissionObjectType=void 0,EnumUserPermissionObjectType=exports.EnumUserPermissionObjectType||(exports.EnumUserPermissionObjectType={}),EnumUserPermissionObjectType.app="App",EnumUserPermissionObjectType.group="Group",EnumUserPermissionObjectType.property="Property",EnumUserPermissionObjectType.unit="Unit";const remapUserResult=e=>{const{tenantIDs:t}=e,n=__rest$4(e,["tenantIDs"]);return Object.assign(Object.assign({},n),{tenantIds:t})},remapEmbeddedUser=e=>e.users?e.users.map(remapUserResult):[];async function userCreate(e,t,n,r){return e.post("/v1/users",Object.assign(Object.assign({},r),{creationContext:t,username:n}))}async function getUsers(e,t=1,n=-1,r={}){const{_embedded:{items:i},total:s}=await e.get("/v1/users",{filter:JSON.stringify(r),limit:n,page:t});return{_embedded:{items:i.map(remapUserResult)},total:s}}async function getCurrentUser(e){return remapUserResult(await e.get("/v1/me"))}async function userGetById(e,t){return remapUserResult(await e.get(`/v1/users/${t}`))}async function userUpdateById(e,t,n){const{tenantIds:r}=n,i=__rest$4(n,["tenantIds"]);return remapUserResult(await e.patch(`/v1/users/${t}`,Object.assign(Object.assign({},i),{tenantIDs:r})))}async function userCreatePermission(e,t,n){const{objectId:r}=n,i=__rest$4(n,["objectId"]),s=await e.post(`/v1/users/${t}/permissions`,Object.assign(Object.assign({},i),{objectID:r})),{objectID:o}=s,a=__rest$4(s,["objectID"]);return Object.assign(Object.assign({},a),{objectId:o})}async function userCreatePermissionBatch(e,t,n){const{objectId:r,objectType:i,roles:s,startDate:o,endDate:a}=n,c={batch:s.map((e=>({endDate:a&&a.toISOString(),objectID:r,objectType:i,restrictions:[],role:e,startDate:o&&o.toISOString()})))};return!await e.post(`/v1/users/${t}/permissions`,c)}async function userGetPermissions(e,t){const{_embedded:{items:n}}=await e.get(`/v1/users/${t}/roles?limit=-1`);return n.map((e=>{var{objectID:t}=e,n=__rest$4(e,["objectID"]);return Object.assign(Object.assign({},n),{objectId:t})}))}async function userDeletePermission(e,t){return!await e.delete(`/v1/permissions/${t}`)}async function userGetUtilisationPeriods(e,t){const{_embedded:{items:n}}=await e.get(`/v1/users/${t}/utilisation-periods`);return n}async function userCheckInToUtilisationPeriod(e,t,n){const{email:r}=await e.userGetById(t);return e.utilisationPeriodCheckInUser(n,{email:r})}async function userGetByEmail(e,t,n=1,r=1e3){return e.getUsers(n,r,{email:t})}async function userChangePassword(e,t,n,r){return!await e.put(`/v1/users/${t}/password`,{currentPassword:n,plainPassword:r})}async function agentCreate(e,t,n,r,i,s,o){const a=await e.userCreate(t,r,Object.assign(Object.assign({},i),{type:EnumUserType.customer})),c=await e.post(`/v1/property-managers/${n}/users`,Object.assign({userID:a.id},o&&{externalAgentCompany:o}));return!((void 0===s||s)&&await e.post(`/v1/users/${a.id}/invitations`))&&Object.assign(Object.assign({},a),c)}async function agentCreatePermissions(e,t,n,r,i,s,o){return e.userCreatePermissionBatch(t,{endDate:o,objectId:n,objectType:r,restrictions:[],roles:i,startDate:s})}async function appCreate(e,t,n){return e.post(`/v1/users/${t}/apps`,Object.assign(Object.assign({availableLocales:{0:"de_DE"}},n),{siteUrl:n.siteUrl.replace("_","")}))}async function appGetById(e,t){return e.get(`/v1/apps/${t}`)}async function activeUnitsGetByAppId(e,t){return e.get(`/v1/apps/${t}/active-units`)}async function bookingGetById(e,t){return e.get(`/v1/bookings/${t}`)}async function bookingUpdateById(e,t,n){return e.patch(`/v1/bookings/${t}`,n)}async function bucketGet(e,t){return e.get(`/v1/buckets/${t}`)}async function bucketCreate(e,t){return e.post("/v1/buckets",{channels:t.channels,name:t.name})}async function bucketAddFile(e,t,n){return""===await e.post(`/v1/buckets/${t}/files`,{id:n})}async function bucketRemoveFile(e,t,n){return""===await e.delete(`/v1/buckets/${t}/files/${n}`)}async function bucketRemoveFilesInPath(e,t,n){return""===await e.delete(`/v1/buckets/${t}/files`,{folder:n.path})}const createManyFiles=async(e,t)=>await Promise.all(e.map((async e=>{try{return await t.fileCreate({file:e.content,name:e.filename})}catch(e){return e}})));async function createManyFilesSorted(e,t){const n=await createManyFiles(e,t);return{error:n.filter((e=>e instanceof Error)),success:n.filter((e=>!(e instanceof Error))).map((e=>e.id))}}async function conversationGetById(e,t){return e.get(`/v1/conversations/${t}`)}async function conversationCreateMessage(e,t,n){const r=`/v1/conversations/${t}/messages`,i=n.attachments&&n.attachments.length?{content:{description:n.body,files:(await createManyFilesSorted(n.attachments,e)).success},createdBy:n.createdBy,inputChannel:n.inputChannel,internal:!1,type:"file"}:{content:{content:n.body},createdBy:n.createdBy,inputChannel:n.inputChannel,type:"text"};return e.post(r,i)}async function fileCreate(e,t){return e.post("/v1/files",{formData:{file:[t.file,t.name],path:t.path||""}})}async function fileDelete(e,t){return""===await e.delete(`/v1/files/${t}`)}var __rest$3=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n};async function groupCreate(e,t,n){const{propertyManagerId:r}=n,i=__rest$3(n,["propertyManagerId"]);return e.post(`/v1/properties/${t}/groups`,Object.assign(Object.assign({},i),{propertyManagerID:r}))}async function groupGetById(e,t){const n=await e.get(`/v1/groups/${t}`),{propertyManagerID:r}=n,i=__rest$3(n,["propertyManagerID"]);return Object.assign(Object.assign({},i),{propertyManagerId:r})}async function groupUpdateById(e,t,n){return e.patch(`/v1/groups/${t}`,n)}async function getGroups(e,t=1,n=-1,r={}){const{_embedded:{items:i},total:s}=await e.get("/v1/groups",{filter:JSON.stringify(r),limit:n,page:t});return{_embedded:{items:i},total:s}}async function lookupIds(e,t,n){return e.post(`/v1/id-lookup/${t}/${n.resource}`,Object.assign(Object.assign({externalIds:"string"==typeof n.externalIds?[n.externalIds]:n.externalIds},n.parentId?{parentId:n.parentId}:{}),n.userType?{userType:n.userType}:{}))}function stringToDate(e){return new Date(Date.parse(e))}function dateToString(e){return e.toISOString()}var __rest$2=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n},EnumNotificationCategory,EnumNotificationType,EnumNotificationSettingsValue;function remapNotificationResult(e){var{createdAt:t,objectID:n,referencedObjectID:r}=e,i=__rest$2(e,["createdAt","objectID","referencedObjectID"]);return Object.assign({createdAt:stringToDate(t),objectId:n,referencedObjectId:r},i)}async function notificationsGetByUser(e,t,n=1,r=-1){const{_embedded:{items:i},total:s,metaData:o}=await e.get(`/v1/users/${t}/notifications?page=${n}&limit=${r}`);return{_embedded:{items:i.map(remapNotificationResult)},metaData:o,total:s}}async function notificationsUpdateReadByUser(e,t,n=new Date){return e.patch(`/v1/users/${t}/notifications`,{lastReadAt:dateToString(n)})}async function notificationUpdateRead(e,t){return remapNotificationResult(await e.patch(`/v1/notifications/${t}`,{read:!0}))}function remapKeys(e,t){return Object.entries(e).reduce(((e,n)=>Object.assign(Object.assign({},e),{[t(n[0])]:n[1]})),{})}function camelCaseToDash(e){return e.replace(/([A-Z])/g,(e=>`-${e[0].toLowerCase()}`))}function dashCaseToCamel(e){return e.replace(/-([a-z])/g,(e=>e[1].toUpperCase()))}async function notificationSettingsUpdateByUser(e,t,n){const r=await e.patch(`/v1/users/${t}/notification-settings`,{notificationSettings:remapKeys(n,camelCaseToDash)});return remapKeys(r,dashCaseToCamel)}async function notificationSettingsResetByUser(e,t){return remapKeys(await e.delete(`/v1/users/${t}/notification-settings`),dashCaseToCamel)}async function propertyCreate(e,t,n){return e.post(`/v1/apps/${t}/properties`,n)}async function propertyGetById(e,t){return e.get(`/v1/properties/${t}`)}async function propertyUpdateById(e,t,n){return e.patch(`/v1/properties/${t}`,n)}async function getProperties(e,t=1,n=-1,r={}){const{_embedded:{items:i},total:s}=await e.get("/v1/properties",{filter:JSON.stringify(r),limit:n,page:t});return{_embedded:{items:i},total:s}}!function(e){e.events="events",e.hintsAndTips="hints-and-tips",e.lostAndFound="lost-and-found",e.localDeals="local-deals",e.localEvents="local-events",e.miscellaneous="miscellaneous",e.deals="deals",e.messages="messages",e.adminMessages="admin-messages",e.newThingsToGive="new-things-to-give",e.newThingsForSale="new-things-for-sale",e.surveys="surveys",e.supportOffer="support-offer",e.supportRequest="support-request",e.sustainability="sustainability",e.localServices="local-services",e.services="services",e.ticketDigestEmail="ticket-digest-email",e.appDigestEmail="app-digest-email",e.newFile="new-file"}(EnumNotificationCategory||(EnumNotificationCategory={})),function(e){e.clipboardThing="clipboard-thing",e.comment="comment",e.communityArticle="community-article",e.newFile="new-file",e.ticketComment="ticket-comment",e.welcomeNotification="welcome-notification"}(EnumNotificationType||(EnumNotificationType={})),function(e){e.never="never",e.immediately="immediately",e.daily="daily",e.weekly="weekly",e.biweekly="biweekly",e.monthly="monthly"}(EnumNotificationSettingsValue||(EnumNotificationSettingsValue={}));var __rest$1=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n};const remapRegistationCodeResult=e=>{const{tenantID:t}=e,n=__rest$1(e,["tenantID"]);return Object.assign(Object.assign({},n),{externalId:t})};async function registrationCodeCreate(e,t,n,r={permanent:!1}){const{externalId:i}=r,s=__rest$1(r,["externalId"]);return remapRegistationCodeResult(await e.post("/v1/registration-codes",Object.assign(Object.assign({code:t,utilisationPeriods:"string"==typeof n?[n]:n},i?{tenantID:i}:{}),s)))}async function registrationCodeUpdateById(e,t,n){return remapRegistationCodeResult(await e.patch(`/v1/registration-codes/${t}`,n))}async function registrationCodeGetById(e,t){return remapRegistationCodeResult(await e.get(`/v1/invitations/${t}`))}async function registrationCodeDelete(e,t){return""===await e.delete(`/v1/invitations/${t}`)}async function serviceProviderCreate(e,t){return e.post("/v1/service-providers",t)}async function serviceProviderGetById(e,t){return e.get(`/v1/service-providers/${t}`)}async function serviceProviderUpdateById(e,t,n){return e.patch(`/v1/service-providers/${t}`,n)}var ETicketStatus,ETrafficLightColor,EnumUnitObjectType,EnumUnitType,EnumUserRelationType;async function ticketGetById(e,t){return e.get(`/v1/tickets/${t}`)}async function ticketCreateOnUser(e,t,n,r){return e.post(`/v1/users/${t}/tickets`,Object.assign(Object.assign({},r),{files:r.files?(await createManyFilesSorted(r.files,e)).success:[],utilisationPeriod:n}))}async function ticketCreateOnServiceProvider(e,t,n){return e.post(`/v1/property-managers/${t}/tickets`,Object.assign(Object.assign({},n),{files:n.files?(await createManyFilesSorted(n.files,e)).success:[]}))}async function unitCreate(e,t,n){return e.post(`/v1/groups/${t}/units`,n)}async function unitGetById(e,t){return e.get(`/v1/units/${t}`)}async function unitUpdateById(e,t,n){return e.patch(`/v1/units/${t}`,n)}async function getUnits(e,t=1,n=-1,r={}){const{_embedded:{items:i},total:s}=await e.get("/v1/units",{filter:JSON.stringify(r),limit:n,page:t});return{_embedded:{items:i},total:s}}async function userRelationCreate(e,t,n){return e.post(`/v1/users/${t}/user-relations/${n.type}`,{ids:n.ids,level:n.level,readOnly:n.readOnly,role:n.role})}async function userRelationDelete(e,t,n){return e.delete(`/v1/users/${t}/user-relations/${n.type}`,{ids:n.ids,level:n.level,role:n.role})}async function userRelationsGetByUser(e,t){return e.get(`/v1/users/${t}/user-relations`)}!function(e){e.CLOSED="closed",e.WAITING_FOR_AGENT="waiting-for-agent",e.WAITING_FOR_CUSTOMER="waiting-for-customer",e.WAITING_FOR_EXTERNAL="waiting-for-external"}(ETicketStatus||(ETicketStatus={})),function(e){e.GREEN="green",e.RED="red",e.YELLOW="yellow"}(ETrafficLightColor||(ETrafficLightColor={})),exports.EnumUnitObjectType=void 0,EnumUnitObjectType=exports.EnumUnitObjectType||(exports.EnumUnitObjectType={}),EnumUnitObjectType.adjoiningRoom="adjoining-room",EnumUnitObjectType.advertisingSpace="advertising-space",EnumUnitObjectType.aerial="aerial",EnumUnitObjectType.apartmentBuilding="apartment-building",EnumUnitObjectType.atm="atm",EnumUnitObjectType.atmRoom="atm-room",EnumUnitObjectType.attic="attic",EnumUnitObjectType.atticFlat="attic-flat",EnumUnitObjectType.bank="bank",EnumUnitObjectType.basment="basment",EnumUnitObjectType.bikeShed="bike-shed",EnumUnitObjectType.buildingLaw="building-law",EnumUnitObjectType.cafeteria="cafeteria",EnumUnitObjectType.caretakerRoom="caretaker-room",EnumUnitObjectType.carport="carport",EnumUnitObjectType.cellar="cellar",EnumUnitObjectType.commercialProperty="commercial-property",EnumUnitObjectType.commonRoom="common-room",EnumUnitObjectType.deliveryZone="delivery-zone",EnumUnitObjectType.diverse="diverse",EnumUnitObjectType.doubleParkingSpace="double-parking-space",EnumUnitObjectType.engineeringRoom="engineering-room",EnumUnitObjectType.entertainment="entertainment",EnumUnitObjectType.environment="environment",EnumUnitObjectType.estate="estate",EnumUnitObjectType.fillingStation="filling-station",EnumUnitObjectType.fitnessCenter="fitness-center",EnumUnitObjectType.flat="flat",EnumUnitObjectType.freeZone="free-zone",EnumUnitObjectType.garage="garage",EnumUnitObjectType.garden="garden",EnumUnitObjectType.gardenFlat="garden-flat",EnumUnitObjectType.heatingFacilities="heating-facilities",EnumUnitObjectType.hotel="hotel",EnumUnitObjectType.incidentalRentalExpenses="incidental-rental-expenses",EnumUnitObjectType.industry="industry",EnumUnitObjectType.kiosk="kiosk",EnumUnitObjectType.kitchen="kitchen",EnumUnitObjectType.loft="loft",EnumUnitObjectType.machine="machine",EnumUnitObjectType.maisonette="maisonette",EnumUnitObjectType.medicalPractice="medical-practice",EnumUnitObjectType.mopedShed="moped-shed",EnumUnitObjectType.motorcycleParkingSpace="motorcycle-parking-space",EnumUnitObjectType.office="office",EnumUnitObjectType.oneFamilyHouse="one-family-house",EnumUnitObjectType.parkingBox="parking-box",EnumUnitObjectType.parkingGarage="parking-garage",EnumUnitObjectType.parkingSpace="parking-space",EnumUnitObjectType.parkingSpaces="parking-spaces",EnumUnitObjectType.penthouse="penthouse",EnumUnitObjectType.productionPlant="production-plant",EnumUnitObjectType.pub="pub",EnumUnitObjectType.publicArea="public-area",EnumUnitObjectType.restaurant="restaurant",EnumUnitObjectType.retirementHome="retirement-home",EnumUnitObjectType.salesFloor="sales-floor",EnumUnitObjectType.school="school",EnumUnitObjectType.shelter="shelter",EnumUnitObjectType.storage="storage",EnumUnitObjectType.store="store",EnumUnitObjectType.storeroom="storeroom",EnumUnitObjectType.studio="studio",EnumUnitObjectType.terrace="terrace",EnumUnitObjectType.toilets="toilets",EnumUnitObjectType.utilityRoom="utility-room",EnumUnitObjectType.variableParkingSpace="variable-parking-space",EnumUnitObjectType.variableRoom="variable-room",EnumUnitObjectType.visitorParkingSpace="visitor-parking-space",EnumUnitObjectType.workshop="workshop",exports.EnumUnitType=void 0,EnumUnitType=exports.EnumUnitType||(exports.EnumUnitType={}),EnumUnitType.rented="rented",EnumUnitType.owned="owned",exports.EnumUserRelationType=void 0,EnumUserRelationType=exports.EnumUserRelationType||(exports.EnumUserRelationType={}),EnumUserRelationType.isResponsible="is-responsible";var __rest=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n},EnumUtilisationPeriodType;async function utilisationPeriodCreate(e,t,n){const r=await e.post(`/v1/units/${t}/utilisation-periods`,n),{tenantIDs:i,_embedded:s}=r,o=__rest(r,["tenantIDs","_embedded"]);return Object.assign(Object.assign({},o),{invitations:s.invitations.map(remapRegistationCodeResult),tenantIds:i,users:remapEmbeddedUser(s)})}async function utilisationPeriodGetById(e,t){const n=await e.get(`/v1/utilisation-periods/${t}`),{tenantIDs:r,_embedded:i}=n,s=__rest(n,["tenantIDs","_embedded"]);return Object.assign(Object.assign({},s),{invitations:i.invitations.map(remapRegistationCodeResult),tenantIds:r,users:remapEmbeddedUser(i)})}async function utilisationPeriodUpdateById(e,t,n){const r=await e.patch(`/v1/utilisation-periods/${t}`,n),{tenantIDs:i,_embedded:s}=r,o=__rest(r,["tenantIDs","_embedded"]);return Object.assign(Object.assign({},o),{invitations:s.invitations.map(remapRegistationCodeResult),tenantIds:i,users:remapEmbeddedUser(s)})}async function utilisationPeriodDelete(e,t){return!await e.delete(`/v1/utilisation-periods/${t}/soft`)}async function utilisationPeriodCheckInUser(e,t,n){return await e.post(`/v1/utilisation-periods/${t}/users`,{email:n.email})&&e.utilisationPeriodGetById(t)}async function utilisationPeriodCheckOutUser(e,t,n){return""===await e.delete(`/v1/utilisation-periods/${t}/users/${n}`)}async function utilisationPeriodAddRegistrationCode(e,t,n,r,i=!1){return e.post(`/v1/utilisation-periods/${t}/registration-codes`,{code:n,permanent:i,tenant:r})}async function patch(e,t,n,r){return e("patch",t,{body:n},r)}async function post(e,t,n,r){return e("post",t,{body:n},r)}async function put(e,t,n,r){return e("put",t,{body:n},r)}exports.EnumUtilisationPeriodType=void 0,EnumUtilisationPeriodType=exports.EnumUtilisationPeriodType||(exports.EnumUtilisationPeriodType={}),EnumUtilisationPeriodType.tenant="tenant",EnumUtilisationPeriodType.ownership="ownership",EnumUtilisationPeriodType.vacant="vacant";var load=function(e,t,n={}){var r,i,s;for(r in t)s=t[r],n[r]=null!=(i=e[r])?i:s;return n},overwrite=function(e,t,n={}){var r,i;for(r in e)i=e[r],void 0!==t[r]&&(n[r]=i);return n},parser$8={load:load,overwrite:overwrite},DLList$2;DLList$2=class{constructor(e,t){this.incr=e,this.decr=t,this._first=null,this._last=null,this.length=0}push(e){var t;this.length++,"function"==typeof this.incr&&this.incr(),t={value:e,prev:this._last,next:null},null!=this._last?(this._last.next=t,this._last=t):this._first=this._last=t}shift(){var e;if(null!=this._first)return this.length--,"function"==typeof this.decr&&this.decr(),e=this._first.value,null!=(this._first=this._first.next)?this._first.prev=null:this._last=null,e}first(){if(null!=this._first)return this._first.value}getArray(){var e,t,n;for(e=this._first,n=[];null!=e;)n.push((t=e,e=e.next,t.value));return n}forEachShift(e){var t;for(t=this.shift();null!=t;)e(t),t=this.shift()}debug(){var e,t,n,r,i;for(e=this._first,i=[];null!=e;)i.push((t=e,e=e.next,{value:t.value,prev:null!=(n=t.prev)?n.value:void 0,next:null!=(r=t.next)?r.value:void 0}));return i}};var DLList_1=DLList$2,Events$6;function asyncGeneratorStep$8(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$8(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$8(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$8(s,r,i,o,a,"throw",e)}o(void 0)}))}}Events$6=class{constructor(e){if(this.instance=e,this._events={},null!=this.instance.on||null!=this.instance.once||null!=this.instance.removeAllListeners)throw new Error("An Emitter already exists for this object");this.instance.on=(e,t)=>this._addListener(e,"many",t),this.instance.once=(e,t)=>this._addListener(e,"once",t),this.instance.removeAllListeners=(e=null)=>null!=e?delete this._events[e]:this._events={}}_addListener(e,t,n){var r;return null==(r=this._events)[e]&&(r[e]=[]),this._events[e].push({cb:n,status:t}),this.instance}listenerCount(e){return null!=this._events[e]?this._events[e].length:0}trigger(e,...t){var n=this;return _asyncToGenerator$8((function*(){var r,i;try{if("debug"!==e&&n.trigger("debug",`Event triggered: ${e}`,t),null==n._events[e])return;return n._events[e]=n._events[e].filter((function(e){return"none"!==e.status})),i=n._events[e].map(function(){var e=_asyncToGenerator$8((function*(e){var r,i;if("none"!==e.status){"once"===e.status&&(e.status="none");try{return"function"==typeof(null!=(i="function"==typeof e.cb?e.cb(...t):void 0)?i.then:void 0)?yield i:i}catch(e){return r=e,n.trigger("error",r),null}}}));return function(t){return e.apply(this,arguments)}}()),(yield Promise.all(i)).find((function(e){return null!=e}))}catch(e){return r=e,n.trigger("error",r),null}}))()}};var Events_1=Events$6,DLList$1,Events$5,Queues$1;DLList$1=DLList_1,Events$5=Events_1,Queues$1=class{constructor(e){this.Events=new Events$5(this),this._length=0,this._lists=function(){var t,n,r;for(r=[],t=1,n=e;1<=n?t<=n:t>=n;1<=n?++t:--t)r.push(new DLList$1((()=>this.incr()),(()=>this.decr())));return r}.call(this)}incr(){if(0==this._length++)return this.Events.trigger("leftzero")}decr(){if(0==--this._length)return this.Events.trigger("zero")}push(e){return this._lists[e.options.priority].push(e)}queued(e){return null!=e?this._lists[e].length:this._length}shiftAll(e){return this._lists.forEach((function(t){return t.forEachShift(e)}))}getFirst(e=this._lists){var t,n,r;for(t=0,n=e.length;t<n;t++)if((r=e[t]).length>0)return r;return[]}shiftLastFrom(e){return this.getFirst(this._lists.slice(e).reverse()).shift()}};var Queues_1=Queues$1,BottleneckError$4;BottleneckError$4=class extends Error{};var BottleneckError_1=BottleneckError$4,BottleneckError$3,DEFAULT_PRIORITY$1,Job$1,NUM_PRIORITIES$1,parser$7;function asyncGeneratorStep$7(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$7(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$7(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$7(s,r,i,o,a,"throw",e)}o(void 0)}))}}NUM_PRIORITIES$1=10,DEFAULT_PRIORITY$1=5,parser$7=parser$8,BottleneckError$3=BottleneckError_1,Job$1=class{constructor(e,t,n,r,i,s,o,a){this.task=e,this.args=t,this.rejectOnDrop=i,this.Events=s,this._states=o,this.Promise=a,this.options=parser$7.load(n,r),this.options.priority=this._sanitizePriority(this.options.priority),this.options.id===r.id&&(this.options.id=`${this.options.id}-${this._randomIndex()}`),this.promise=new this.Promise(((e,t)=>{this._resolve=e,this._reject=t})),this.retryCount=0}_sanitizePriority(e){var t;return(t=~~e!==e?DEFAULT_PRIORITY$1:e)<0?0:t>NUM_PRIORITIES$1-1?NUM_PRIORITIES$1-1:t}_randomIndex(){return Math.random().toString(36).slice(2)}doDrop({error:e,message:t="This job has been dropped by Bottleneck"}={}){return!!this._states.remove(this.options.id)&&(this.rejectOnDrop&&this._reject(null!=e?e:new BottleneckError$3(t)),this.Events.trigger("dropped",{args:this.args,options:this.options,task:this.task,promise:this.promise}),!0)}_assertStatus(e){var t;if((t=this._states.jobStatus(this.options.id))!==e&&("DONE"!==e||null!==t))throw new BottleneckError$3(`Invalid job status ${t}, expected ${e}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`)}doReceive(){return this._states.start(this.options.id),this.Events.trigger("received",{args:this.args,options:this.options})}doQueue(e,t){return this._assertStatus("RECEIVED"),this._states.next(this.options.id),this.Events.trigger("queued",{args:this.args,options:this.options,reachedHWM:e,blocked:t})}doRun(){return 0===this.retryCount?(this._assertStatus("QUEUED"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),this.Events.trigger("scheduled",{args:this.args,options:this.options})}doExecute(e,t,n,r){var i=this;return _asyncToGenerator$7((function*(){var s,o,a;0===i.retryCount?(i._assertStatus("RUNNING"),i._states.next(i.options.id)):i._assertStatus("EXECUTING"),o={args:i.args,options:i.options,retryCount:i.retryCount},i.Events.trigger("executing",o);try{if(a=yield null!=e?e.schedule(i.options,i.task,...i.args):i.task(...i.args),t())return i.doDone(o),yield r(i.options,o),i._assertStatus("DONE"),i._resolve(a)}catch(e){return s=e,i._onFailure(s,o,t,n,r)}}))()}doExpire(e,t,n){var r,i;return this._states.jobStatus("RUNNING"===this.options.id)&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),i={args:this.args,options:this.options,retryCount:this.retryCount},r=new BottleneckError$3(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(r,i,e,t,n)}_onFailure(e,t,n,r,i){var s=this;return _asyncToGenerator$7((function*(){var o,a;if(n())return null!=(o=yield s.Events.trigger("failed",e,t))?(a=~~o,s.Events.trigger("retry",`Retrying ${s.options.id} after ${a} ms`,t),s.retryCount++,r(a)):(s.doDone(t),yield i(s.options,t),s._assertStatus("DONE"),s._reject(e))}))()}doDone(e){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",e)}};var Job_1=Job$1,BottleneckError$2,LocalDatastore$1,parser$6;function asyncGeneratorStep$6(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$6(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$6(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$6(s,r,i,o,a,"throw",e)}o(void 0)}))}}parser$6=parser$8,BottleneckError$2=BottleneckError_1,LocalDatastore$1=class{constructor(e,t,n){this.instance=e,this.storeOptions=t,this.clientId=this.instance._randomIndex(),parser$6.load(n,n,this),this._nextRequest=this._lastReservoirRefresh=this._lastReservoirIncrease=Date.now(),this._running=0,this._done=0,this._unblockTime=0,this.ready=this.Promise.resolve(),this.clients={},this._startHeartbeat()}_startHeartbeat(){var e;return null==this.heartbeat&&(null!=this.storeOptions.reservoirRefreshInterval&&null!=this.storeOptions.reservoirRefreshAmount||null!=this.storeOptions.reservoirIncreaseInterval&&null!=this.storeOptions.reservoirIncreaseAmount)?"function"==typeof(e=this.heartbeat=setInterval((()=>{var e,t,n,r,i;if(r=Date.now(),null!=this.storeOptions.reservoirRefreshInterval&&r>=this._lastReservoirRefresh+this.storeOptions.reservoirRefreshInterval&&(this._lastReservoirRefresh=r,this.storeOptions.reservoir=this.storeOptions.reservoirRefreshAmount,this.instance._drainAll(this.computeCapacity())),null!=this.storeOptions.reservoirIncreaseInterval&&r>=this._lastReservoirIncrease+this.storeOptions.reservoirIncreaseInterval){var s=this.storeOptions;if(e=s.reservoirIncreaseAmount,n=s.reservoirIncreaseMaximum,i=s.reservoir,this._lastReservoirIncrease=r,(t=null!=n?Math.min(e,n-i):e)>0)return this.storeOptions.reservoir+=t,this.instance._drainAll(this.computeCapacity())}}),this.heartbeatInterval)).unref?e.unref():void 0:clearInterval(this.heartbeat)}__publish__(e){var t=this;return _asyncToGenerator$6((function*(){return yield t.yieldLoop(),t.instance.Events.trigger("message",e.toString())}))()}__disconnect__(e){var t=this;return _asyncToGenerator$6((function*(){return yield t.yieldLoop(),clearInterval(t.heartbeat),t.Promise.resolve()}))()}yieldLoop(e=0){return new this.Promise((function(t,n){return setTimeout(t,e)}))}computePenalty(){var e;return null!=(e=this.storeOptions.penalty)?e:15*this.storeOptions.minTime||5e3}__updateSettings__(e){var t=this;return _asyncToGenerator$6((function*(){return yield t.yieldLoop(),parser$6.overwrite(e,e,t.storeOptions),t._startHeartbeat(),t.instance._drainAll(t.computeCapacity()),!0}))()}__running__(){var e=this;return _asyncToGenerator$6((function*(){return yield e.yieldLoop(),e._running}))()}__queued__(){var e=this;return _asyncToGenerator$6((function*(){return yield e.yieldLoop(),e.instance.queued()}))()}__done__(){var e=this;return _asyncToGenerator$6((function*(){return yield e.yieldLoop(),e._done}))()}__groupCheck__(e){var t=this;return _asyncToGenerator$6((function*(){return yield t.yieldLoop(),t._nextRequest+t.timeout<e}))()}computeCapacity(){var e,t,n=this.storeOptions;return e=n.maxConcurrent,t=n.reservoir,null!=e&&null!=t?Math.min(e-this._running,t):null!=e?e-this._running:null!=t?t:null}conditionsCheck(e){var t;return null==(t=this.computeCapacity())||e<=t}__incrementReservoir__(e){var t=this;return _asyncToGenerator$6((function*(){var n;return yield t.yieldLoop(),n=t.storeOptions.reservoir+=e,t.instance._drainAll(t.computeCapacity()),n}))()}__currentReservoir__(){var e=this;return _asyncToGenerator$6((function*(){return yield e.yieldLoop(),e.storeOptions.reservoir}))()}isBlocked(e){return this._unblockTime>=e}check(e,t){return this.conditionsCheck(e)&&this._nextRequest-t<=0}__check__(e){var t=this;return _asyncToGenerator$6((function*(){var n;return yield t.yieldLoop(),n=Date.now(),t.check(e,n)}))()}__register__(e,t,n){var r=this;return _asyncToGenerator$6((function*(){var e,n;return yield r.yieldLoop(),e=Date.now(),r.conditionsCheck(t)?(r._running+=t,null!=r.storeOptions.reservoir&&(r.storeOptions.reservoir-=t),n=Math.max(r._nextRequest-e,0),r._nextRequest=e+n+r.storeOptions.minTime,{success:!0,wait:n,reservoir:r.storeOptions.reservoir}):{success:!1}}))()}strategyIsBlock(){return 3===this.storeOptions.strategy}__submit__(e,t){var n=this;return _asyncToGenerator$6((function*(){var r,i,s;if(yield n.yieldLoop(),null!=n.storeOptions.maxConcurrent&&t>n.storeOptions.maxConcurrent)throw new BottleneckError$2(`Impossible to add a job having a weight of ${t} to a limiter having a maxConcurrent setting of ${n.storeOptions.maxConcurrent}`);return i=Date.now(),s=null!=n.storeOptions.highWater&&e===n.storeOptions.highWater&&!n.check(t,i),(r=n.strategyIsBlock()&&(s||n.isBlocked(i)))&&(n._unblockTime=i+n.computePenalty(),n._nextRequest=n._unblockTime+n.storeOptions.minTime,n.instance._dropAllQueued()),{reachedHWM:s,blocked:r,strategy:n.storeOptions.strategy}}))()}__free__(e,t){var n=this;return _asyncToGenerator$6((function*(){return yield n.yieldLoop(),n._running-=t,n._done+=t,n.instance._drainAll(n.computeCapacity()),{running:n._running}}))()}};var LocalDatastore_1=LocalDatastore$1,lua={"blacklist_client.lua":"local blacklist = ARGV[num_static_argv + 1]\n\nif redis.call('zscore', client_last_seen_key, blacklist) then\n redis.call('zadd', client_last_seen_key, 0, blacklist)\nend\n\n\nreturn {}\n","check.lua":"local weight = tonumber(ARGV[num_static_argv + 1])\n\nlocal capacity = process_tick(now, false)['capacity']\nlocal nextRequest = tonumber(redis.call('hget', settings_key, 'nextRequest'))\n\nreturn conditions_check(capacity, weight) and nextRequest - now <= 0\n","conditions_check.lua":"local conditions_check = function (capacity, weight)\n return capacity == nil or weight <= capacity\nend\n","current_reservoir.lua":"return process_tick(now, false)['reservoir']\n","done.lua":"process_tick(now, false)\n\nreturn tonumber(redis.call('hget', settings_key, 'done'))\n","free.lua":"local index = ARGV[num_static_argv + 1]\n\nredis.call('zadd', job_expirations_key, 0, index)\n\nreturn process_tick(now, false)['running']\n","get_time.lua":"redis.replicate_commands()\n\nlocal get_time = function ()\n local time = redis.call('time')\n\n return tonumber(time[1]..string.sub(time[2], 1, 3))\nend\n","group_check.lua":"return not (redis.call('exists', settings_key) == 1)\n","heartbeat.lua":"process_tick(now, true)\n","increment_reservoir.lua":"local incr = tonumber(ARGV[num_static_argv + 1])\n\nredis.call('hincrby', settings_key, 'reservoir', incr)\n\nlocal reservoir = process_tick(now, true)['reservoir']\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn reservoir\n","init.lua":"local clear = tonumber(ARGV[num_static_argv + 1])\nlocal limiter_version = ARGV[num_static_argv + 2]\nlocal num_local_argv = num_static_argv + 2\n\nif clear == 1 then\n redis.call('del', unpack(KEYS))\nend\n\nif redis.call('exists', settings_key) == 0 then\n -- Create\n local args = {'hmset', settings_key}\n\n for i = num_local_argv + 1, #ARGV do\n table.insert(args, ARGV[i])\n end\n\n redis.call(unpack(args))\n redis.call('hmset', settings_key,\n 'nextRequest', now,\n 'lastReservoirRefresh', now,\n 'lastReservoirIncrease', now,\n 'running', 0,\n 'done', 0,\n 'unblockTime', 0,\n 'capacityPriorityCounter', 0\n )\n\nelse\n -- Apply migrations\n local settings = redis.call('hmget', settings_key,\n 'id',\n 'version'\n )\n local id = settings[1]\n local current_version = settings[2]\n\n if current_version ~= limiter_version then\n local version_digits = {}\n for k, v in string.gmatch(current_version, \"([^.]+)\") do\n table.insert(version_digits, tonumber(k))\n end\n\n -- 2.10.0\n if version_digits[2] < 10 then\n redis.call('hsetnx', settings_key, 'reservoirRefreshInterval', '')\n redis.call('hsetnx', settings_key, 'reservoirRefreshAmount', '')\n redis.call('hsetnx', settings_key, 'lastReservoirRefresh', '')\n redis.call('hsetnx', settings_key, 'done', 0)\n redis.call('hset', settings_key, 'version', '2.10.0')\n end\n\n -- 2.11.1\n if version_digits[2] < 11 or (version_digits[2] == 11 and version_digits[3] < 1) then\n if redis.call('hstrlen', settings_key, 'lastReservoirRefresh') == 0 then\n redis.call('hmset', settings_key,\n 'lastReservoirRefresh', now,\n 'version', '2.11.1'\n )\n end\n end\n\n -- 2.14.0\n if version_digits[2] < 14 then\n local old_running_key = 'b_'..id..'_running'\n local old_executing_key = 'b_'..id..'_executing'\n\n if redis.call('exists', old_running_key) == 1 then\n redis.call('rename', old_running_key, job_weights_key)\n end\n if redis.call('exists', old_executing_key) == 1 then\n redis.call('rename', old_executing_key, job_expirations_key)\n end\n redis.call('hset', settings_key, 'version', '2.14.0')\n end\n\n -- 2.15.2\n if version_digits[2] < 15 or (version_digits[2] == 15 and version_digits[3] < 2) then\n redis.call('hsetnx', settings_key, 'capacityPriorityCounter', 0)\n redis.call('hset', settings_key, 'version', '2.15.2')\n end\n\n -- 2.17.0\n if version_digits[2] < 17 then\n redis.call('hsetnx', settings_key, 'clientTimeout', 10000)\n redis.call('hset', settings_key, 'version', '2.17.0')\n end\n\n -- 2.18.0\n if version_digits[2] < 18 then\n redis.call('hsetnx', settings_key, 'reservoirIncreaseInterval', '')\n redis.call('hsetnx', settings_key, 'reservoirIncreaseAmount', '')\n redis.call('hsetnx', settings_key, 'reservoirIncreaseMaximum', '')\n redis.call('hsetnx', settings_key, 'lastReservoirIncrease', now)\n redis.call('hset', settings_key, 'version', '2.18.0')\n end\n\n end\n\n process_tick(now, false)\nend\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn {}\n","process_tick.lua":"local process_tick = function (now, always_publish)\n\n local compute_capacity = function (maxConcurrent, running, reservoir)\n if maxConcurrent ~= nil and reservoir ~= nil then\n return math.min((maxConcurrent - running), reservoir)\n elseif maxConcurrent ~= nil then\n return maxConcurrent - running\n elseif reservoir ~= nil then\n return reservoir\n else\n return nil\n end\n end\n\n local settings = redis.call('hmget', settings_key,\n 'id',\n 'maxConcurrent',\n 'running',\n 'reservoir',\n 'reservoirRefreshInterval',\n 'reservoirRefreshAmount',\n 'lastReservoirRefresh',\n 'reservoirIncreaseInterval',\n 'reservoirIncreaseAmount',\n 'reservoirIncreaseMaximum',\n 'lastReservoirIncrease',\n 'capacityPriorityCounter',\n 'clientTimeout'\n )\n local id = settings[1]\n local maxConcurrent = tonumber(settings[2])\n local running = tonumber(settings[3])\n local reservoir = tonumber(settings[4])\n local reservoirRefreshInterval = tonumber(settings[5])\n local reservoirRefreshAmount = tonumber(settings[6])\n local lastReservoirRefresh = tonumber(settings[7])\n local reservoirIncreaseInterval = tonumber(settings[8])\n local reservoirIncreaseAmount = tonumber(settings[9])\n local reservoirIncreaseMaximum = tonumber(settings[10])\n local lastReservoirIncrease = tonumber(settings[11])\n local capacityPriorityCounter = tonumber(settings[12])\n local clientTimeout = tonumber(settings[13])\n\n local initial_capacity = compute_capacity(maxConcurrent, running, reservoir)\n\n --\n -- Process 'running' changes\n --\n local expired = redis.call('zrangebyscore', job_expirations_key, '-inf', '('..now)\n\n if #expired > 0 then\n redis.call('zremrangebyscore', job_expirations_key, '-inf', '('..now)\n\n local flush_batch = function (batch, acc)\n local weights = redis.call('hmget', job_weights_key, unpack(batch))\n redis.call('hdel', job_weights_key, unpack(batch))\n local clients = redis.call('hmget', job_clients_key, unpack(batch))\n redis.call('hdel', job_clients_key, unpack(batch))\n\n -- Calculate sum of removed weights\n for i = 1, #weights do\n acc['total'] = acc['total'] + (tonumber(weights[i]) or 0)\n end\n\n -- Calculate sum of removed weights by client\n local client_weights = {}\n for i = 1, #clients do\n local removed = tonumber(weights[i]) or 0\n if removed > 0 then\n acc['client_weights'][clients[i]] = (acc['client_weights'][clients[i]] or 0) + removed\n end\n end\n end\n\n local acc = {\n ['total'] = 0,\n ['client_weights'] = {}\n }\n local batch_size = 1000\n\n -- Compute changes to Zsets and apply changes to Hashes\n for i = 1, #expired, batch_size do\n local batch = {}\n for j = i, math.min(i + batch_size - 1, #expired) do\n table.insert(batch, expired[j])\n end\n\n flush_batch(batch, acc)\n end\n\n -- Apply changes to Zsets\n if acc['total'] > 0 then\n redis.call('hincrby', settings_key, 'done', acc['total'])\n running = tonumber(redis.call('hincrby', settings_key, 'running', -acc['total']))\n end\n\n for client, weight in pairs(acc['client_weights']) do\n redis.call('zincrby', client_running_key, -weight, client)\n end\n end\n\n --\n -- Process 'reservoir' changes\n --\n local reservoirRefreshActive = reservoirRefreshInterval ~= nil and reservoirRefreshAmount ~= nil\n if reservoirRefreshActive and now >= lastReservoirRefresh + reservoirRefreshInterval then\n reservoir = reservoirRefreshAmount\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'lastReservoirRefresh', now\n )\n end\n\n local reservoirIncreaseActive = reservoirIncreaseInterval ~= nil and reservoirIncreaseAmount ~= nil\n if reservoirIncreaseActive and now >= lastReservoirIncrease + reservoirIncreaseInterval then\n local num_intervals = math.floor((now - lastReservoirIncrease) / reservoirIncreaseInterval)\n local incr = reservoirIncreaseAmount * num_intervals\n if reservoirIncreaseMaximum ~= nil then\n incr = math.min(incr, reservoirIncreaseMaximum - (reservoir or 0))\n end\n if incr > 0 then\n reservoir = (reservoir or 0) + incr\n end\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'lastReservoirIncrease', lastReservoirIncrease + (num_intervals * reservoirIncreaseInterval)\n )\n end\n\n --\n -- Clear unresponsive clients\n --\n local unresponsive = redis.call('zrangebyscore', client_last_seen_key, '-inf', (now - clientTimeout))\n local unresponsive_lookup = {}\n local terminated_clients = {}\n for i = 1, #unresponsive do\n unresponsive_lookup[unresponsive[i]] = true\n if tonumber(redis.call('zscore', client_running_key, unresponsive[i])) == 0 then\n table.insert(terminated_clients, unresponsive[i])\n end\n end\n if #terminated_clients > 0 then\n redis.call('zrem', client_running_key, unpack(terminated_clients))\n redis.call('hdel', client_num_queued_key, unpack(terminated_clients))\n redis.call('zrem', client_last_registered_key, unpack(terminated_clients))\n redis.call('zrem', client_last_seen_key, unpack(terminated_clients))\n end\n\n --\n -- Broadcast capacity changes\n --\n local final_capacity = compute_capacity(maxConcurrent, running, reservoir)\n\n if always_publish or (initial_capacity ~= nil and final_capacity == nil) then\n -- always_publish or was not unlimited, now unlimited\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\n\n elseif initial_capacity ~= nil and final_capacity ~= nil and final_capacity > initial_capacity then\n -- capacity was increased\n -- send the capacity message to the limiter having the lowest number of running jobs\n -- the tiebreaker is the limiter having not registered a job in the longest time\n\n local lowest_concurrency_value = nil\n local lowest_concurrency_clients = {}\n local lowest_concurrency_last_registered = {}\n local client_concurrencies = redis.call('zrange', client_running_key, 0, -1, 'withscores')\n\n for i = 1, #client_concurrencies, 2 do\n local client = client_concurrencies[i]\n local concurrency = tonumber(client_concurrencies[i+1])\n\n if (\n lowest_concurrency_value == nil or lowest_concurrency_value == concurrency\n ) and (\n not unresponsive_lookup[client]\n ) and (\n tonumber(redis.call('hget', client_num_queued_key, client)) > 0\n ) then\n lowest_concurrency_value = concurrency\n table.insert(lowest_concurrency_clients, client)\n local last_registered = tonumber(redis.call('zscore', client_last_registered_key, client))\n table.insert(lowest_concurrency_last_registered, last_registered)\n end\n end\n\n if #lowest_concurrency_clients > 0 then\n local position = 1\n local earliest = lowest_concurrency_last_registered[1]\n\n for i,v in ipairs(lowest_concurrency_last_registered) do\n if v < earliest then\n position = i\n earliest = v\n end\n end\n\n local next_client = lowest_concurrency_clients[position]\n redis.call('publish', 'b_'..id,\n 'capacity-priority:'..(final_capacity or '')..\n ':'..next_client..\n ':'..capacityPriorityCounter\n )\n redis.call('hincrby', settings_key, 'capacityPriorityCounter', '1')\n else\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\n end\n end\n\n return {\n ['capacity'] = final_capacity,\n ['running'] = running,\n ['reservoir'] = reservoir\n }\nend\n","queued.lua":"local clientTimeout = tonumber(redis.call('hget', settings_key, 'clientTimeout'))\nlocal valid_clients = redis.call('zrangebyscore', client_last_seen_key, (now - clientTimeout), 'inf')\nlocal client_queued = redis.call('hmget', client_num_queued_key, unpack(valid_clients))\n\nlocal sum = 0\nfor i = 1, #client_queued do\n sum = sum + tonumber(client_queued[i])\nend\n\nreturn sum\n","refresh_expiration.lua":"local refresh_expiration = function (now, nextRequest, groupTimeout)\n\n if groupTimeout ~= nil then\n local ttl = (nextRequest + groupTimeout) - now\n\n for i = 1, #KEYS do\n redis.call('pexpire', KEYS[i], ttl)\n end\n end\n\nend\n","refs.lua":"local settings_key = KEYS[1]\nlocal job_weights_key = KEYS[2]\nlocal job_expirations_key = KEYS[3]\nlocal job_clients_key = KEYS[4]\nlocal client_running_key = KEYS[5]\nlocal client_num_queued_key = KEYS[6]\nlocal client_last_registered_key = KEYS[7]\nlocal client_last_seen_key = KEYS[8]\n\nlocal now = tonumber(ARGV[1])\nlocal client = ARGV[2]\n\nlocal num_static_argv = 2\n","register.lua":"local index = ARGV[num_static_argv + 1]\nlocal weight = tonumber(ARGV[num_static_argv + 2])\nlocal expiration = tonumber(ARGV[num_static_argv + 3])\n\nlocal state = process_tick(now, false)\nlocal capacity = state['capacity']\nlocal reservoir = state['reservoir']\n\nlocal settings = redis.call('hmget', settings_key,\n 'nextRequest',\n 'minTime',\n 'groupTimeout'\n)\nlocal nextRequest = tonumber(settings[1])\nlocal minTime = tonumber(settings[2])\nlocal groupTimeout = tonumber(settings[3])\n\nif conditions_check(capacity, weight) then\n\n redis.call('hincrby', settings_key, 'running', weight)\n redis.call('hset', job_weights_key, index, weight)\n if expiration ~= nil then\n redis.call('zadd', job_expirations_key, now + expiration, index)\n end\n redis.call('hset', job_clients_key, index, client)\n redis.call('zincrby', client_running_key, weight, client)\n redis.call('hincrby', client_num_queued_key, client, -1)\n redis.call('zadd', client_last_registered_key, now, client)\n\n local wait = math.max(nextRequest - now, 0)\n local newNextRequest = now + wait + minTime\n\n if reservoir == nil then\n redis.call('hset', settings_key,\n 'nextRequest', newNextRequest\n )\n else\n reservoir = reservoir - weight\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'nextRequest', newNextRequest\n )\n end\n\n refresh_expiration(now, newNextRequest, groupTimeout)\n\n return {true, wait, reservoir}\n\nelse\n return {false}\nend\n","register_client.lua":"local queued = tonumber(ARGV[num_static_argv + 1])\n\n-- Could have been re-registered concurrently\nif not redis.call('zscore', client_last_seen_key, client) then\n redis.call('zadd', client_running_key, 0, client)\n redis.call('hset', client_num_queued_key, client, queued)\n redis.call('zadd', client_last_registered_key, 0, client)\nend\n\nredis.call('zadd', client_last_seen_key, now, client)\n\nreturn {}\n","running.lua":"return process_tick(now, false)['running']\n","submit.lua":"local queueLength = tonumber(ARGV[num_static_argv + 1])\nlocal weight = tonumber(ARGV[num_static_argv + 2])\n\nlocal capacity = process_tick(now, false)['capacity']\n\nlocal settings = redis.call('hmget', settings_key,\n 'id',\n 'maxConcurrent',\n 'highWater',\n 'nextRequest',\n 'strategy',\n 'unblockTime',\n 'penalty',\n 'minTime',\n 'groupTimeout'\n)\nlocal id = settings[1]\nlocal maxConcurrent = tonumber(settings[2])\nlocal highWater = tonumber(settings[3])\nlocal nextRequest = tonumber(settings[4])\nlocal strategy = tonumber(settings[5])\nlocal unblockTime = tonumber(settings[6])\nlocal penalty = tonumber(settings[7])\nlocal minTime = tonumber(settings[8])\nlocal groupTimeout = tonumber(settings[9])\n\nif maxConcurrent ~= nil and weight > maxConcurrent then\n return redis.error_reply('OVERWEIGHT:'..weight..':'..maxConcurrent)\nend\n\nlocal reachedHWM = (highWater ~= nil and queueLength == highWater\n and not (\n conditions_check(capacity, weight)\n and nextRequest - now <= 0\n )\n)\n\nlocal blocked = strategy == 3 and (reachedHWM or unblockTime >= now)\n\nif blocked then\n local computedPenalty = penalty\n if computedPenalty == nil then\n if minTime == 0 then\n computedPenalty = 5000\n else\n computedPenalty = 15 * minTime\n end\n end\n\n local newNextRequest = now + computedPenalty + minTime\n\n redis.call('hmset', settings_key,\n 'unblockTime', now + computedPenalty,\n 'nextRequest', newNextRequest\n )\n\n local clients_queued_reset = redis.call('hkeys', client_num_queued_key)\n local queued_reset = {}\n for i = 1, #clients_queued_reset do\n table.insert(queued_reset, clients_queued_reset[i])\n table.insert(queued_reset, 0)\n end\n redis.call('hmset', client_num_queued_key, unpack(queued_reset))\n\n redis.call('publish', 'b_'..id, 'blocked:')\n\n refresh_expiration(now, newNextRequest, groupTimeout)\nend\n\nif not blocked and not reachedHWM then\n redis.call('hincrby', client_num_queued_key, client, 1)\nend\n\nreturn {reachedHWM, blocked, strategy}\n","update_settings.lua":"local args = {'hmset', settings_key}\n\nfor i = num_static_argv + 1, #ARGV do\n table.insert(args, ARGV[i])\nend\n\nredis.call(unpack(args))\n\nprocess_tick(now, true)\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn {}\n","validate_client.lua":"if not redis.call('zscore', client_last_seen_key, client) then\n return redis.error_reply('UNKNOWN_CLIENT')\nend\n\nredis.call('zadd', client_last_seen_key, now, client)\n","validate_keys.lua":"if not (redis.call('exists', settings_key) == 1) then\n return redis.error_reply('SETTINGS_KEY_NOT_FOUND')\nend\n"},lua$1=Object.freeze({__proto__:null,default:lua}),require$$0=getCjsExportFromNamespace(lua$1),Scripts$3=createCommonjsModule((function(e,t){var n,r,i;n={refs:(r=require$$0)["refs.lua"],validate_keys:r["validate_keys.lua"],validate_client:r["validate_client.lua"],refresh_expiration:r["refresh_expiration.lua"],process_tick:r["process_tick.lua"],conditions_check:r["conditions_check.lua"],get_time:r["get_time.lua"]},t.allKeys=function(e){return[`b_${e}_settings`,`b_${e}_job_weights`,`b_${e}_job_expirations`,`b_${e}_job_clients`,`b_${e}_client_running`,`b_${e}_client_num_queued`,`b_${e}_client_last_registered`,`b_${e}_client_last_seen`]},i={init:{keys:t.allKeys,headers:["process_tick"],refresh_expiration:!0,code:r["init.lua"]},group_check:{keys:t.allKeys,headers:[],refresh_expiration:!1,code:r["group_check.lua"]},register_client:{keys:t.allKeys,headers:["validate_keys"],refresh_expiration:!1,code:r["register_client.lua"]},blacklist_client:{keys:t.allKeys,headers:["validate_keys","validate_client"],refresh_expiration:!1,code:r["blacklist_client.lua"]},heartbeat:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:r["heartbeat.lua"]},update_settings:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:r["update_settings.lua"]},running:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:r["running.lua"]},queued:{keys:t.allKeys,headers:["validate_keys","validate_client"],refresh_expiration:!1,code:r["queued.lua"]},done:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:r["done.lua"]},check:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!1,code:r["check.lua"]},submit:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!0,code:r["submit.lua"]},register:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!0,code:r["register.lua"]},free:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:r["free.lua"]},current_reservoir:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:r["current_reservoir.lua"]},increment_reservoir:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:r["increment_reservoir.lua"]}},t.names=Object.keys(i),t.keys=function(e,t){return i[e].keys(t)},t.payload=function(e){var t;return t=i[e],Array.prototype.concat(n.refs,t.headers.map((function(e){return n[e]})),t.refresh_expiration?n.refresh_expiration:"",t.code).join("\n")}})),Events$4,RedisConnection$2,Scripts$2,parser$5;function asyncGeneratorStep$5(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$5(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$5(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$5(s,r,i,o,a,"throw",e)}o(void 0)}))}}Scripts$3.allKeys,Scripts$3.names,Scripts$3.keys,Scripts$3.payload,parser$5=parser$8,Events$4=Events_1,Scripts$2=Scripts$3,RedisConnection$2=function(){class RedisConnection{constructor(options={}){parser$5.load(options,this.defaults,this),null==this.Redis&&(this.Redis=eval("require")("redis")),null==this.Events&&(this.Events=new Events$4(this)),this.terminated=!1,null==this.client&&(this.client=this.Redis.createClient(this.clientOptions)),this.subscriber=this.client.duplicate(),this.limiters={},this.shas={},this.ready=this.Promise.all([this._setup(this.client,!1),this._setup(this.subscriber,!0)]).then((()=>this._loadScripts())).then((()=>({client:this.client,subscriber:this.subscriber})))}_setup(e,t){return e.setMaxListeners(0),new this.Promise(((n,r)=>(e.on("error",(e=>this.Events.trigger("error",e))),t&&e.on("message",((e,t)=>{var n;return null!=(n=this.limiters[e])?n._store.onMessage(e,t):void 0})),e.ready?n():e.once("ready",n))))}_loadScript(e){return new this.Promise(((t,n)=>{var r;return r=Scripts$2.payload(e),this.client.multi([["script","load",r]]).exec(((r,i)=>null!=r?n(r):(this.shas[e]=i[0],t(i[0]))))}))}_loadScripts(){return this.Promise.all(Scripts$2.names.map((e=>this._loadScript(e))))}__runCommand__(e){var t=this;return _asyncToGenerator$5((function*(){return yield t.ready,new t.Promise(((n,r)=>t.client.multi([e]).exec_atomic((function(e,t){return null!=e?r(e):n(t[0])}))))}))()}__addLimiter__(e){return this.Promise.all([e.channel(),e.channel_client()].map((t=>new this.Promise(((n,r)=>{var i;return i=r=>{if(r===t)return this.subscriber.removeListener("subscribe",i),this.limiters[t]=e,n()},this.subscriber.on("subscribe",i),this.subscriber.subscribe(t)})))))}__removeLimiter__(e){var t=this;return this.Promise.all([e.channel(),e.channel_client()].map(function(){var e=_asyncToGenerator$5((function*(e){return t.terminated||(yield new t.Promise(((n,r)=>t.subscriber.unsubscribe(e,(function(t,i){return null!=t?r(t):i===e?n():void 0}))))),delete t.limiters[e]}));return function(t){return e.apply(this,arguments)}}()))}__scriptArgs__(e,t,n,r){var i;return i=Scripts$2.keys(e,t),[this.shas[e],i.length].concat(i,n,r)}__scriptFn__(e){return this.client.evalsha.bind(this.client)}disconnect(e=!0){var t,n,r,i;for(t=0,r=(i=Object.keys(this.limiters)).length;t<r;t++)n=i[t],clearInterval(this.limiters[n]._store.heartbeat);return this.limiters={},this.terminated=!0,this.client.end(e),this.subscriber.end(e),this.Promise.resolve()}}return RedisConnection.prototype.datastore="redis",RedisConnection.prototype.defaults={Redis:null,clientOptions:{},client:null,Promise:Promise,Events:null},RedisConnection}.call(void 0);var RedisConnection_1=RedisConnection$2,Events$3,IORedisConnection$2,Scripts$1,parser$4;function _slicedToArray$3(e,t){return _arrayWithHoles$3(e)||_iterableToArrayLimit$3(e,t)||_nonIterableRest$3()}function _nonIterableRest$3(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArrayLimit$3(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function _arrayWithHoles$3(e){if(Array.isArray(e))return e}function asyncGeneratorStep$4(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$4(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$4(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$4(s,r,i,o,a,"throw",e)}o(void 0)}))}}parser$4=parser$8,Events$3=Events_1,Scripts$1=Scripts$3,IORedisConnection$2=function(){class IORedisConnection{constructor(options={}){parser$4.load(options,this.defaults,this),null==this.Redis&&(this.Redis=eval("require")("ioredis")),null==this.Events&&(this.Events=new Events$3(this)),this.terminated=!1,null!=this.clusterNodes?(this.client=new this.Redis.Cluster(this.clusterNodes,this.clientOptions),this.subscriber=new this.Redis.Cluster(this.clusterNodes,this.clientOptions)):null!=this.client&&null==this.client.duplicate?this.subscriber=new this.Redis.Cluster(this.client.startupNodes,this.client.options):(null==this.client&&(this.client=new this.Redis(this.clientOptions)),this.subscriber=this.client.duplicate()),this.limiters={},this.ready=this.Promise.all([this._setup(this.client,!1),this._setup(this.subscriber,!0)]).then((()=>(this._loadScripts(),{client:this.client,subscriber:this.subscriber})))}_setup(e,t){return e.setMaxListeners(0),new this.Promise(((n,r)=>(e.on("error",(e=>this.Events.trigger("error",e))),t&&e.on("message",((e,t)=>{var n;return null!=(n=this.limiters[e])?n._store.onMessage(e,t):void 0})),"ready"===e.status?n():e.once("ready",n))))}_loadScripts(){return Scripts$1.names.forEach((e=>this.client.defineCommand(e,{lua:Scripts$1.payload(e)})))}__runCommand__(e){var t=this;return _asyncToGenerator$4((function*(){yield t.ready;var n=_slicedToArray$3(yield t.client.pipeline([e]).exec(),1),r=_slicedToArray$3(n[0],2);return r[0],r[1]}))()}__addLimiter__(e){return this.Promise.all([e.channel(),e.channel_client()].map((t=>new this.Promise(((n,r)=>this.subscriber.subscribe(t,(()=>(this.limiters[t]=e,n()))))))))}__removeLimiter__(e){var t=this;return[e.channel(),e.channel_client()].forEach(function(){var e=_asyncToGenerator$4((function*(e){return t.terminated||(yield t.subscriber.unsubscribe(e)),delete t.limiters[e]}));return function(t){return e.apply(this,arguments)}}())}__scriptArgs__(e,t,n,r){var i;return[(i=Scripts$1.keys(e,t)).length].concat(i,n,r)}__scriptFn__(e){return this.client[e].bind(this.client)}disconnect(e=!0){var t,n,r,i;for(t=0,r=(i=Object.keys(this.limiters)).length;t<r;t++)n=i[t],clearInterval(this.limiters[n]._store.heartbeat);return this.limiters={},this.terminated=!0,e?this.Promise.all([this.client.quit(),this.subscriber.quit()]):(this.client.disconnect(),this.subscriber.disconnect(),this.Promise.resolve())}}return IORedisConnection.prototype.datastore="ioredis",IORedisConnection.prototype.defaults={Redis:null,clientOptions:{},clusterNodes:null,client:null,Promise:Promise,Events:null},IORedisConnection}.call(void 0);var IORedisConnection_1=IORedisConnection$2,BottleneckError$1,IORedisConnection$1,RedisConnection$1,RedisDatastore$1,parser$3;function _slicedToArray$2(e,t){return _arrayWithHoles$2(e)||_iterableToArrayLimit$2(e,t)||_nonIterableRest$2()}function _nonIterableRest$2(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArrayLimit$2(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function _arrayWithHoles$2(e){if(Array.isArray(e))return e}function asyncGeneratorStep$3(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$3(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$3(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$3(s,r,i,o,a,"throw",e)}o(void 0)}))}}parser$3=parser$8,BottleneckError$1=BottleneckError_1,RedisConnection$1=RedisConnection_1,IORedisConnection$1=IORedisConnection_1,RedisDatastore$1=class{constructor(e,t,n){this.instance=e,this.storeOptions=t,this.originalId=this.instance.id,this.clientId=this.instance._randomIndex(),parser$3.load(n,n,this),this.clients={},this.capacityPriorityCounters={},this.sharedConnection=null!=this.connection,null==this.connection&&(this.connection="redis"===this.instance.datastore?new RedisConnection$1({Redis:this.Redis,clientOptions:this.clientOptions,Promise:this.Promise,Events:this.instance.Events}):"ioredis"===this.instance.datastore?new IORedisConnection$1({Redis:this.Redis,clientOptions:this.clientOptions,clusterNodes:this.clusterNodes,Promise:this.Promise,Events:this.instance.Events}):void 0),this.instance.connection=this.connection,this.instance.datastore=this.connection.datastore,this.ready=this.connection.ready.then((e=>(this.clients=e,this.runScript("init",this.prepareInitSettings(this.clearDatastore))))).then((()=>this.connection.__addLimiter__(this.instance))).then((()=>this.runScript("register_client",[this.instance.queued()]))).then((()=>{var e;return"function"==typeof(e=this.heartbeat=setInterval((()=>this.runScript("heartbeat",[]).catch((e=>this.instance.Events.trigger("error",e)))),this.heartbeatInterval)).unref&&e.unref(),this.clients}))}__publish__(e){var t=this;return _asyncToGenerator$3((function*(){return(yield t.ready).client.publish(t.instance.channel(),`message:${e.toString()}`)}))()}onMessage(e,t){var n=this;return _asyncToGenerator$3((function*(){var e,r,i,s,o,a,c,u,l,d;try{c=t.indexOf(":");var p=[t.slice(0,c),t.slice(c+1)];if(i=p[1],"capacity"===(d=p[0]))return yield n.instance._drainAll(i.length>0?~~i:void 0);if("capacity-priority"===d){var h=_slicedToArray$2(i.split(":"),3);return l=h[0],u=h[1],r=h[2],e=l.length>0?~~l:void 0,u===n.clientId?(s=yield n.instance._drainAll(e),a=null!=e?e-(s||0):"",yield n.clients.client.publish(n.instance.channel(),`capacity-priority:${a}::${r}`)):""===u?(clearTimeout(n.capacityPriorityCounters[r]),delete n.capacityPriorityCounters[r],n.instance._drainAll(e)):n.capacityPriorityCounters[r]=setTimeout(_asyncToGenerator$3((function*(){var t;try{return delete n.capacityPriorityCounters[r],yield n.runScript("blacklist_client",[u]),yield n.instance._drainAll(e)}catch(e){return t=e,n.instance.Events.trigger("error",t)}})),1e3)}if("message"===d)return n.instance.Events.trigger("message",i);if("blocked"===d)return yield n.instance._dropAllQueued()}catch(e){return o=e,n.instance.Events.trigger("error",o)}}))()}__disconnect__(e){return clearInterval(this.heartbeat),this.sharedConnection?this.connection.__removeLimiter__(this.instance):this.connection.disconnect(e)}runScript(e,t){var n=this;return _asyncToGenerator$3((function*(){return"init"!==e&&"register_client"!==e&&(yield n.ready),new n.Promise(((r,i)=>{var s,o;return s=[Date.now(),n.clientId].concat(t),n.instance.Events.trigger("debug",`Calling Redis script: ${e}.lua`,s),o=n.connection.__scriptArgs__(e,n.originalId,s,(function(e,t){return null!=e?i(e):r(t)})),n.connection.__scriptFn__(e)(...o)})).catch((r=>"SETTINGS_KEY_NOT_FOUND"===r.message?"heartbeat"===e?n.Promise.resolve():n.runScript("init",n.prepareInitSettings(!1)).then((()=>n.runScript(e,t))):"UNKNOWN_CLIENT"===r.message?n.runScript("register_client",[n.instance.queued()]).then((()=>n.runScript(e,t))):n.Promise.reject(r)))}))()}prepareArray(e){var t,n,r,i;for(r=[],t=0,n=e.length;t<n;t++)i=e[t],r.push(null!=i?i.toString():"");return r}prepareObject(e){var t,n,r;for(n in t=[],e)r=e[n],t.push(n,null!=r?r.toString():"");return t}prepareInitSettings(e){var t;return(t=this.prepareObject(Object.assign({},this.storeOptions,{id:this.originalId,version:this.instance.version,groupTimeout:this.timeout,clientTimeout:this.clientTimeout}))).unshift(e?1:0,this.instance.version),t}convertBool(e){return!!e}__updateSettings__(e){var t=this;return _asyncToGenerator$3((function*(){return yield t.runScript("update_settings",t.prepareObject(e)),parser$3.overwrite(e,e,t.storeOptions)}))()}__running__(){return this.runScript("running",[])}__queued__(){return this.runScript("queued",[])}__done__(){return this.runScript("done",[])}__groupCheck__(){var e=this;return _asyncToGenerator$3((function*(){return e.convertBool(yield e.runScript("group_check",[]))}))()}__incrementReservoir__(e){return this.runScript("increment_reservoir",[e])}__currentReservoir__(){return this.runScript("current_reservoir",[])}__check__(e){var t=this;return _asyncToGenerator$3((function*(){return t.convertBool(yield t.runScript("check",t.prepareArray([e])))}))()}__register__(e,t,n){var r=this;return _asyncToGenerator$3((function*(){var i,s,o,a=_slicedToArray$2(yield r.runScript("register",r.prepareArray([e,t,n])),3);return s=a[0],o=a[1],i=a[2],{success:r.convertBool(s),wait:o,reservoir:i}}))()}__submit__(e,t){var n=this;return _asyncToGenerator$3((function*(){var r,i,s,o,a;try{var c=_slicedToArray$2(yield n.runScript("submit",n.prepareArray([e,t])),3);return o=c[0],r=c[1],a=c[2],{reachedHWM:n.convertBool(o),blocked:n.convertBool(r),strategy:a}}catch(e){if(0===(i=e).message.indexOf("OVERWEIGHT")){var u=_slicedToArray$2(i.message.split(":"),3);throw u[0],t=u[1],s=u[2],new BottleneckError$1(`Impossible to add a job having a weight of ${t} to a limiter having a maxConcurrent setting of ${s}`)}throw i}}))()}__free__(e,t){var n=this;return _asyncToGenerator$3((function*(){return{running:yield n.runScript("free",n.prepareArray([e]))}}))()}};var RedisDatastore_1=RedisDatastore$1,BottleneckError,States$1;BottleneckError=BottleneckError_1,States$1=class{constructor(e){this.status=e,this._jobs={},this.counts=this.status.map((function(){return 0}))}next(e){var t,n;return n=(t=this._jobs[e])+1,null!=t&&n<this.status.length?(this.counts[t]--,this.counts[n]++,this._jobs[e]++):null!=t?(this.counts[t]--,delete this._jobs[e]):void 0}start(e){return 0,this._jobs[e]=0,this.counts[0]++}remove(e){var t;return null!=(t=this._jobs[e])&&(this.counts[t]--,delete this._jobs[e]),null!=t}jobStatus(e){var t;return null!=(t=this.status[this._jobs[e]])?t:null}statusJobs(e){var t,n,r,i;if(null!=e){if((n=this.status.indexOf(e))<0)throw new BottleneckError(`status must be one of ${this.status.join(", ")}`);for(t in i=[],r=this._jobs)r[t]===n&&i.push(t);return i}return Object.keys(this._jobs)}statusCounts(){return this.counts.reduce(((e,t,n)=>(e[this.status[n]]=t,e)),{})}};var States_1=States$1,DLList,Sync$1;function asyncGeneratorStep$2(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$2(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$2(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$2(s,r,i,o,a,"throw",e)}o(void 0)}))}}DLList=DLList_1,Sync$1=class{constructor(e,t){this.schedule=this.schedule.bind(this),this.name=e,this.Promise=t,this._running=0,this._queue=new DLList}isEmpty(){return 0===this._queue.length}_tryToRun(){var e=this;return _asyncToGenerator$2((function*(){var t,n,r,i,s,o,a;if(e._running<1&&e._queue.length>0){e._running++;var c=e._queue.shift();return a=c.task,t=c.args,s=c.resolve,i=c.reject,n=yield _asyncToGenerator$2((function*(){try{return o=yield a(...t),function(){return s(o)}}catch(e){return r=e,function(){return i(r)}}}))(),e._running--,e._tryToRun(),n()}}))()}schedule(e,...t){var n,r,i;return i=r=null,n=new this.Promise((function(e,t){return i=e,r=t})),this._queue.push({task:e,args:t,resolve:i,reject:r}),this._tryToRun(),n}};var Sync_1=Sync$1;const version="2.19.5";var version$1={version:version},version$2=Object.freeze({__proto__:null,default:version$1,version:version}),Events$2,Group,IORedisConnection,RedisConnection,Scripts,parser$2;function _slicedToArray$1(e,t){return _arrayWithHoles$1(e)||_iterableToArrayLimit$1(e,t)||_nonIterableRest$1()}function _nonIterableRest$1(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArrayLimit$1(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function _arrayWithHoles$1(e){if(Array.isArray(e))return e}function asyncGeneratorStep$1(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator$1(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep$1(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep$1(s,r,i,o,a,"throw",e)}o(void 0)}))}}parser$2=parser$8,Events$2=Events_1,RedisConnection=RedisConnection_1,IORedisConnection=IORedisConnection_1,Scripts=Scripts$3,Group=function(){class e{constructor(e={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=e,parser$2.load(this.limiterOptions,this.defaults,this),this.Events=new Events$2(this),this.instances={},this.Bottleneck=Bottleneck_1,this._startAutoCleanup(),this.sharedConnection=null!=this.connection,null==this.connection&&("redis"===this.limiterOptions.datastore?this.connection=new RedisConnection(Object.assign({},this.limiterOptions,{Events:this.Events})):"ioredis"===this.limiterOptions.datastore&&(this.connection=new IORedisConnection(Object.assign({},this.limiterOptions,{Events:this.Events}))))}key(e=""){var t;return null!=(t=this.instances[e])?t:(()=>{var t;return t=this.instances[e]=new this.Bottleneck(Object.assign(this.limiterOptions,{id:`${this.id}-${e}`,timeout:this.timeout,connection:this.connection})),this.Events.trigger("created",t,e),t})()}deleteKey(e=""){var t=this;return _asyncToGenerator$1((function*(){var n,r;return r=t.instances[e],t.connection&&(n=yield t.connection.__runCommand__(["del",...Scripts.allKeys(`${t.id}-${e}`)])),null!=r&&(delete t.instances[e],yield r.disconnect()),null!=r||n>0}))()}limiters(){var e,t,n,r;for(e in n=[],t=this.instances)r=t[e],n.push({key:e,limiter:r});return n}keys(){return Object.keys(this.instances)}clusterKeys(){var e=this;return _asyncToGenerator$1((function*(){var t,n,r,i,s,o,a,c;if(null==e.connection)return e.Promise.resolve(e.keys());for(o=[],t=null,c=`b_${e.id}-`.length,n="_settings".length;0!==t;){var u=_slicedToArray$1(yield e.connection.__runCommand__(["scan",null!=t?t:0,"match",`b_${e.id}-*_settings`,"count",1e4]),2);for(t=~~u[0],i=0,a=(r=u[1]).length;i<a;i++)s=r[i],o.push(s.slice(c,-n))}return o}))()}_startAutoCleanup(){var e,t=this;return clearInterval(this.interval),"function"==typeof(e=this.interval=setInterval(_asyncToGenerator$1((function*(){var e,n,r,i,s,o;for(n in s=Date.now(),i=[],r=t.instances){o=r[n];try{(yield o._store.__groupCheck__(s))?i.push(t.deleteKey(n)):i.push(void 0)}catch(t){e=t,i.push(o.Events.trigger("error",e))}}return i})),this.timeout/2)).unref?e.unref():void 0}updateSettings(e={}){if(parser$2.overwrite(e,this.defaults,this),parser$2.overwrite(e,e,this.limiterOptions),null!=e.timeout)return this._startAutoCleanup()}disconnect(e=!0){var t;if(!this.sharedConnection)return null!=(t=this.connection)?t.disconnect(e):void 0}}return e.prototype.defaults={timeout:3e5,connection:null,Promise:Promise,id:"group-key"},e}.call(void 0);var Group_1=Group,Batcher,Events$1,parser$1;parser$1=parser$8,Events$1=Events_1,Batcher=function(){class e{constructor(e={}){this.options=e,parser$1.load(this.options,this.defaults,this),this.Events=new Events$1(this),this._arr=[],this._resetPromise(),this._lastFlush=Date.now()}_resetPromise(){return this._promise=new this.Promise(((e,t)=>this._resolve=e))}_flush(){return clearTimeout(this._timeout),this._lastFlush=Date.now(),this._resolve(),this.Events.trigger("batch",this._arr),this._arr=[],this._resetPromise()}add(e){var t;return this._arr.push(e),t=this._promise,this._arr.length===this.maxSize?this._flush():null!=this.maxTime&&1===this._arr.length&&(this._timeout=setTimeout((()=>this._flush()),this.maxTime)),t}}return e.prototype.defaults={maxTime:null,maxSize:null,Promise:Promise},e}.call(void 0);var Batcher_1=Batcher,require$$8=getCjsExportFromNamespace(version$2);function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_nonIterableRest()}function _iterableToArrayLimit(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function _toArray(e){return _arrayWithHoles(e)||_iterableToArray(e)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}function _arrayWithHoles(e){if(Array.isArray(e))return e}function asyncGeneratorStep(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep(s,r,i,o,a,"throw",e)}o(void 0)}))}}var Bottleneck,DEFAULT_PRIORITY,Events,Job,LocalDatastore,NUM_PRIORITIES,Queues,RedisDatastore,States,Sync,parser,splice=[].splice;NUM_PRIORITIES=10,DEFAULT_PRIORITY=5,parser=parser$8,Queues=Queues_1,Job=Job_1,LocalDatastore=LocalDatastore_1,RedisDatastore=RedisDatastore_1,Events=Events_1,States=States_1,Sync=Sync_1,Bottleneck=function(){class e{constructor(t={},...n){var r,i;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(t,n),parser.load(t,this.instanceDefaults,this),this._queues=new Queues(NUM_PRIORITIES),this._scheduled={},this._states=new States(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new Events(this),this._submitLock=new Sync("submit",this.Promise),this._registerLock=new Sync("register",this.Promise),i=parser.load(t,this.storeDefaults,{}),this._store=function(){if("redis"===this.datastore||"ioredis"===this.datastore||null!=this.connection)return r=parser.load(t,this.redisStoreDefaults,{}),new RedisDatastore(this,i,r);if("local"===this.datastore)return r=parser.load(t,this.localStoreDefaults,{}),new LocalDatastore(this,i,r);throw new e.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`)}.call(this),this._queues.on("leftzero",(()=>{var e;return null!=(e=this._store.heartbeat)&&"function"==typeof e.ref?e.ref():void 0})),this._queues.on("zero",(()=>{var e;return null!=(e=this._store.heartbeat)&&"function"==typeof e.unref?e.unref():void 0}))}_validateOptions(t,n){if(null==t||"object"!=typeof t||0!==n.length)throw new e.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.")}ready(){return this._store.ready}clients(){return this._store.clients}channel(){return`b_${this.id}`}channel_client(){return`b_${this.id}_${this._store.clientId}`}publish(e){return this._store.__publish__(e)}disconnect(e=!0){return this._store.__disconnect__(e)}chain(e){return this._limiter=e,this}queued(e){return this._queues.queued(e)}clusterQueued(){return this._store.__queued__()}empty(){return 0===this.queued()&&this._submitLock.isEmpty()}running(){return this._store.__running__()}done(){return this._store.__done__()}jobStatus(e){return this._states.jobStatus(e)}jobs(e){return this._states.statusJobs(e)}counts(){return this._states.statusCounts()}_randomIndex(){return Math.random().toString(36).slice(2)}check(e=1){return this._store.__check__(e)}_clearGlobalState(e){return null!=this._scheduled[e]&&(clearTimeout(this._scheduled[e].expiration),delete this._scheduled[e],!0)}_free(e,t,n,r){var i=this;return _asyncToGenerator((function*(){var t,s;try{if(s=(yield i._store.__free__(e,n.weight)).running,i.Events.trigger("debug",`Freed ${n.id}`,r),0===s&&i.empty())return i.Events.trigger("idle")}catch(e){return t=e,i.Events.trigger("error",t)}}))()}_run(e,t,n){var r,i,s;return t.doRun(),r=this._clearGlobalState.bind(this,e),s=this._run.bind(this,e,t),i=this._free.bind(this,e,t),this._scheduled[e]={timeout:setTimeout((()=>t.doExecute(this._limiter,r,s,i)),n),expiration:null!=t.options.expiration?setTimeout((function(){return t.doExpire(r,s,i)}),n+t.options.expiration):void 0,job:t}}_drainOne(e){return this._registerLock.schedule((()=>{var t,n,r,i,s;if(0===this.queued())return this.Promise.resolve(null);s=this._queues.getFirst();var o=r=s.first();return i=o.options,t=o.args,null!=e&&i.weight>e?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${i.id}`,{args:t,options:i}),n=this._randomIndex(),this._store.__register__(n,i.weight,i.expiration).then((({success:e,wait:o,reservoir:a})=>{var c;return this.Events.trigger("debug",`Drained ${i.id}`,{success:e,args:t,options:i}),e?(s.shift(),(c=this.empty())&&this.Events.trigger("empty"),0===a&&this.Events.trigger("depleted",c),this._run(n,r,o),this.Promise.resolve(i.weight)):this.Promise.resolve(null)})))}))}_drainAll(e,t=0){return this._drainOne(e).then((n=>{var r;return null!=n?(r=null!=e?e-n:e,this._drainAll(r,t+n)):this.Promise.resolve(t)})).catch((e=>this.Events.trigger("error",e)))}_dropAllQueued(e){return this._queues.shiftAll((function(t){return t.doDrop({message:e})}))}stop(t={}){var n,r;return t=parser.load(t,this.stopDefaults),r=e=>{var t;return t=()=>{var t;return(t=this._states.counts)[0]+t[1]+t[2]+t[3]===e},new this.Promise(((e,n)=>t()?e():this.on("done",(()=>{if(t())return this.removeAllListeners("done"),e()}))))},n=t.dropWaitingJobs?(this._run=function(e,n){return n.doDrop({message:t.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule((()=>this._submitLock.schedule((()=>{var e,n,i;for(e in n=this._scheduled)i=n[e],"RUNNING"===this.jobStatus(i.job.options.id)&&(clearTimeout(i.timeout),clearTimeout(i.expiration),i.job.doDrop({message:t.dropErrorMessage}));return this._dropAllQueued(t.dropErrorMessage),r(0)}))))):this.schedule({priority:NUM_PRIORITIES-1,weight:0},(()=>r(1))),this._receive=function(n){return n._reject(new e.prototype.BottleneckError(t.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new e.prototype.BottleneckError("stop() has already been called")),n}_addToQueue(t){var n=this;return _asyncToGenerator((function*(){var r,i,s,o,a,c,u;r=t.args,o=t.options;try{var l=yield n._store.__submit__(n.queued(),o.weight);a=l.reachedHWM,i=l.blocked,u=l.strategy}catch(e){return s=e,n.Events.trigger("debug",`Could not queue ${o.id}`,{args:r,options:o,error:s}),t.doDrop({error:s}),!1}return i?(t.doDrop(),!0):a&&(null!=(c=u===e.prototype.strategy.LEAK?n._queues.shiftLastFrom(o.priority):u===e.prototype.strategy.OVERFLOW_PRIORITY?n._queues.shiftLastFrom(o.priority+1):u===e.prototype.strategy.OVERFLOW?t:void 0)&&c.doDrop(),null==c||u===e.prototype.strategy.OVERFLOW)?(null==c&&t.doDrop(),a):(t.doQueue(a,i),n._queues.push(t),yield n._drainAll(),a)}))()}_receive(t){return null!=this._states.jobStatus(t.options.id)?(t._reject(new e.prototype.BottleneckError(`A job with the same id already exists (id=${t.options.id})`)),!1):(t.doReceive(),this._submitLock.schedule(this._addToQueue,t))}submit(...e){var t,n,r,i,s,o,a,c,u;"function"==typeof e[0]?(o=_toArray(e),n=o[0],e=o.slice(1),a=_slicedToArray(splice.call(e,-1),1),t=a[0],i=parser.load({},this.jobDefaults)):(i=(c=_toArray(e))[0],n=c[1],e=c.slice(2),u=_slicedToArray(splice.call(e,-1),1),t=u[0],i=parser.load(i,this.jobDefaults));return s=(...e)=>new this.Promise((function(t,r){return n(...e,(function(...e){return(null!=e[0]?r:t)(e)}))})),(r=new Job(s,e,i,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise)).promise.then((function(e){return"function"==typeof t?t(...e):void 0})).catch((function(e){return Array.isArray(e)?"function"==typeof t?t(...e):void 0:"function"==typeof t?t(e):void 0})),this._receive(r)}schedule(...e){var t,n,r;if("function"==typeof e[0]){var i=_toArray(e);r=i[0],e=i.slice(1),n={}}else{var s=_toArray(e);n=s[0],r=s[1],e=s.slice(2)}return t=new Job(r,e,n,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(t),t.promise}wrap(e){var t,n;return t=this.schedule.bind(this),(n=function(...n){return t(e.bind(this),...n)}).withOptions=function(n,...r){return t(n,e,...r)},n}updateSettings(e={}){var t=this;return _asyncToGenerator((function*(){return yield t._store.__updateSettings__(parser.overwrite(e,t.storeDefaults)),parser.overwrite(e,t.instanceDefaults,t),t}))()}currentReservoir(){return this._store.__currentReservoir__()}incrementReservoir(e=0){return this._store.__incrementReservoir__(e)}}return e.default=e,e.Events=Events,e.version=e.prototype.version=require$$8.version,e.strategy=e.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},e.BottleneckError=e.prototype.BottleneckError=BottleneckError_1,e.Group=e.prototype.Group=Group_1,e.RedisConnection=e.prototype.RedisConnection=RedisConnection_1,e.IORedisConnection=e.prototype.IORedisConnection=IORedisConnection_1,e.Batcher=e.prototype.Batcher=Batcher_1,e.prototype.jobDefaults={priority:DEFAULT_PRIORITY,weight:1,expiration:null,id:"<no-id>"},e.prototype.storeDefaults={maxConcurrent:null,minTime:0,highWater:null,strategy:e.prototype.strategy.LEAK,penalty:null,reservoir:null,reservoirRefreshInterval:null,reservoirRefreshAmount:null,reservoirIncreaseInterval:null,reservoirIncreaseAmount:null,reservoirIncreaseMaximum:null},e.prototype.localStoreDefaults={Promise:Promise,timeout:null,heartbeatInterval:250},e.prototype.redisStoreDefaults={Promise:Promise,timeout:null,heartbeatInterval:5e3,clientTimeout:1e4,Redis:null,clientOptions:{},clusterNodes:null,clearDatastore:!1,connection:null},e.prototype.instanceDefaults={datastore:"local",connection:null,id:"<no-id>",rejectOnDrop:!0,trackDoneStatus:!1,Promise:Promise},e.prototype.stopDefaults={enqueueErrorMessage:"This limiter has been stopped and cannot accept new jobs.",dropWaitingJobs:!0,dropErrorMessage:"This limiter has been stopped."},e}.call(void 0);var Bottleneck_1=Bottleneck,lib=Bottleneck_1,browser="object"==typeof self?self.FormData:window.FormData;const GRANT_TYPE$1="client_credentials",castClientOptionsToRequestParams=e=>{const{scope:t,clientId:n,clientSecret:r}=e;if(!n)throw new Error('Missing required "clientId" parameter to perform client credentials grant');if(!r)throw new Error('Missing required "clientSecret" parameter to perform client credentials grant');return Object.assign({client_id:n,client_secret:r,grant_type:GRANT_TYPE$1},t?{scope:t}:{})},isEligible$1=e=>{try{return!!castClientOptionsToRequestParams(e)}catch(e){return!1}},requestToken$1=(e,t)=>e(castClientOptionsToRequestParams(t)),RESPONSE_TYPE="token",castToAuthorizationRequestParams=e=>{const{clientId:t,scope:n,state:r,redirectUri:i}=e;if(!t)throw new Error('Missing required "clientId" parameter to perform implicit grant');return Object.assign(Object.assign({client_id:t,redirect_uri:i||window.location.href,response_type:RESPONSE_TYPE},n?{scope:n}:{}),r?{state:r}:{})},isEligibleForClientRedirect=e=>{try{return!!castToAuthorizationRequestParams(e)}catch(e){return!1}},getRedirectUrl=e=>`${e.oauthUrl}/oauth/authorize?${queryString.stringify(castToAuthorizationRequestParams(e),{skipNull:!0,skipEmptyString:!0})}`,GRANT_TYPE="password",castToTokenRequestParams=e=>{const{username:t,password:n,scope:r,clientId:i,clientSecret:s}=e;if(!i)throw new Error('Missing required "clientId" parameter to perform password grant');if(!t)throw new Error('Missing required "username" parameter to perform password grant');if(!n)throw new Error('Missing required "password" parameter to perform password grant');return Object.assign(Object.assign({client_id:i,grant_type:GRANT_TYPE,password:n,username:t},r?{scope:r}:{}),s?{client_secret:s}:{})},isEligible=e=>{try{return!!castToTokenRequestParams(e)}catch(e){return!1}},requestToken=(e,t)=>e(castToTokenRequestParams(t));async function maybeUpdateToken(e,t,n,r=!1){if(!r&&e.get("accessToken"))return;const i=Object.assign(Object.assign({},n),{refreshToken:e.get("refreshToken")});if(isEligible$2(i))return e.set(await requestToken$2(t,i));if(isEligible(n))return e.set(await requestToken(t,n));if("undefined"!=typeof window&&n.implicit){const t=queryString.parse(window.location.hash),r=t&&t.access_token;if(r)return window.history.replaceState({},"",window.location.href.split("#")[0]),e.set({accessToken:r});if(isEligibleForClientRedirect(n))return void(window.location.href=getRedirectUrl(n))}return!r&&isEligible$3(n)?e.set(await requestToken$3(t,n)):n.authorizationRedirect&&isEligibleForClientRedirect$1(n)?n.authorizationRedirect(getRedirectUrl$1(n)):isEligible$1(n)?e.set(await requestToken$1(t,n)):void 0}function sleep(e){return new Promise((t=>setTimeout((()=>t(!0)),e)))}const requestLogger=makeLogger("REST API Request"),responseLogger=makeLogger("REST API Response"),RETRYABLE_STATUS_CODES=[401,408,429,502,503,504],TOKEN_REFRESH_STATUS_CODES=[401],queue=new lib({maxConcurrent:QUEUE_CONCURRENCY,minTime:QUEUE_DELAY,reservoir:QUEUE_RESERVOIR}),refillIntervalSet=new Set;function isFormData(e){return void 0!==e&&void 0!==e.formData}function refillReservoir(){if(0===refillIntervalSet.size){const e=setInterval((async()=>{const t=await queue.currentReservoir();return queue.empty()&&0===await queue.running()&&t>10?await queue.incrementReservoir(1)&&fnClearInterval(e)&&refillIntervalSet.delete(e):t<QUEUE_RESERVOIR?queue.incrementReservoir(1):fnClearInterval(e)&&refillIntervalSet.delete(e)}),QUEUE_RESERVOIR_REFILL_INTERVAL);return refillIntervalSet.add(e)}return refillIntervalSet}async function makeResultFromResponse(e){return RETRYABLE_STATUS_CODES.includes(e.status)?e.clone():e.ok?"application/json"!==e.headers.get("content-type")&&204!==e.status?new Error(`Response content type was "${e.headers.get("content-type")}" but expected JSON`):{body:204===e.status?"":await e.json(),status:e.status}:new Error(`${e.status} ${e.statusText}\n\n${await e.text()}`)}function responseWasSuccessful(e){return!RETRYABLE_STATUS_CODES.includes(e.status)}function makeApiRequest(e,t,n,r,i,s,o){return async(a,c)=>{if(c>0){if(c>n.requestMaxRetries){const e=`Maximum number of retries reached while retrying ${a.method} request ${a.path}.`;throw requestLogger.error(e),new Error(e)}requestLogger.warn(`Warning: encountered ${a.status}. Retrying ${a.method} request ${a.path} (retry #${c}).`),await sleep(Math.ceil(Math.random()*n.requestBackOffInterval*2**c))}if(await maybeUpdateToken(e,t,n,c>0&&TOKEN_REFRESH_STATUS_CODES.includes(a.status)),!e.get("accessToken"))throw new Error("Unable to get OAuth2 access token.");try{return refillReservoir()&&await queue.schedule((async()=>{const t=r.toUpperCase(),a=s&&s.query?(i.includes("?")?"&":"?")+queryString.stringify(s.query,{skipNull:!0,skipEmptyString:!0}):"",c=`${n.apiUrl}/api${i}${a}`,u=s&&s.body,l=isFormData(u),d=isFormData(u)?u.formData:{},p=Object.entries(d).reduce(((e,[t,n])=>(e.append.apply(e,[t].concat(n)),e)),new browser),h=Object.assign(Object.assign(Object.assign(Object.assign({accept:"application/json",authorization:`Bearer ${e.get("accessToken")}`},l?{}:{"content-type":"application/json"}),"undefined"==typeof window&&"undefined"==typeof document&&{"user-agent":USER_AGENT}),s&&s.headers?s.headers:{}),l&&p.getHeaders?p.getHeaders():{});[].DEBUG&&console.log({sdkLogs:{method:t,url:c}}),requestLogger.log(t,c,{body:u,headers:h});const m={body:l?p:JSON.stringify(u)},y=await fetch(c,Object.assign({cache:"no-cache",credentials:"omit",headers:h,method:t,mode:"cors"},l||u?m:{})),_=await makeResultFromResponse(y);return responseLogger.log(t,c,_ instanceof Error?{error:_}:{body:_.body,status:y.status}),_ instanceof Error&&o?{body:_.message,status:y.status}:_}))}catch(e){return e}}}async function request(e,t,n,r,i,s,o){const a=await until(responseWasSuccessful,makeApiRequest(e,t,n,r,i,s,o));if(a instanceof Error)throw requestLogger.log("Request Error",a,s),a;return o?a:a.body}const API_METHODS=[agentCreate,agentCreatePermissions,activeUnitsGetByAppId,appCreate,appGetById,bucketCreate,bucketAddFile,bucketRemoveFile,bucketRemoveFilesInPath,bucketGet,conversationGetById,conversationCreateMessage,fileCreate,fileDelete,notificationSettingsResetByUser,notificationSettingsUpdateByUser,groupCreate,groupGetById,groupUpdateById,getGroups,lookupIds,notificationsGetByUser,notificationUpdateRead,notificationsUpdateReadByUser,propertyCreate,propertyGetById,propertyUpdateById,getProperties,serviceProviderCreate,serviceProviderGetById,serviceProviderUpdateById,registrationCodeCreate,registrationCodeUpdateById,registrationCodeDelete,registrationCodeGetById,ticketCreateOnUser,ticketCreateOnServiceProvider,ticketGetById,unitCreate,unitGetById,unitUpdateById,getUnits,userCreate,userGetById,userUpdateById,userChangePassword,userCreatePermission,userCreatePermissionBatch,userGetPermissions,userDeletePermission,userCheckInToUtilisationPeriod,userGetUtilisationPeriods,userGetByEmail,getCurrentUser,getUsers,userRelationCreate,userRelationDelete,userRelationsGetByUser,utilisationPeriodCreate,utilisationPeriodDelete,utilisationPeriodGetById,utilisationPeriodUpdateById,utilisationPeriodCheckInUser,utilisationPeriodCheckOutUser,utilisationPeriodAddRegistrationCode,bookingUpdateById,bookingGetById];function restClient(e=DEFAULT_API_WRAPPER_OPTIONS){const t=Object.assign(Object.assign({},DEFAULT_API_WRAPPER_OPTIONS),e);if(void 0===t.apiUrl)throw new Error("API URL is undefined.");if(void 0===t.oauthUrl)throw new Error("OAuth2 URL is undefined.");if(!t.clientId&&!t.accessToken&&!t.tokenStore&&"undefined"==typeof window)throw new Error('Missing required "clientId" or "accessToken" parameter .');const n=makeFetchTokenRequester(`${t.oauthUrl}/oauth/token`),r=t.tokenStore||createTokenStore({accessToken:t.accessToken,refreshToken:t.refreshToken}),i=partial(request,r,n,t),s=partial(del,i),o=partial(get,i),a=partial(post,i),c=partial(patch,i),u=partial(put,i),l={authorizationCode:{getUri:(e=t.state||pseudoRandomString())=>partial(getRedirectUrl$1,Object.assign(Object.assign({},t),{state:e}))(),requestToken:e=>requestAndSaveToStore(partial(requestToken$3,n,Object.assign(Object.assign({},t),{authorizationCode:e||t.authorizationCode})),r)},generateState:pseudoRandomString,refreshToken:e=>requestAndSaveToStore(partial(requestToken$2,n,Object.assign(Object.assign({},t),{refreshToken:e||r.get("refreshToken")})),r)},d=API_METHODS.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:(...e)=>t(d,...e)})),{delete:s,get:o,oauth:l,options:t,patch:c,post:a,put:u});return d}var EnumResource,EnumCountryCode,EnumLocale,EnumTimezone,EnumServiceProviderType,EnumCommunicationMethodType,EnumInputChannel,EnumLookupUserType;exports.EnumResource=void 0,EnumResource=exports.EnumResource||(exports.EnumResource={}),EnumResource.group="group",EnumResource.property="property",EnumResource.serviceProvider="propertyManager",EnumResource.registrationCode="registrationCode",EnumResource.unit="unit",EnumResource.user="user",EnumResource.utilisationPeriod="utilisationPeriod",exports.EnumCountryCode=void 0,EnumCountryCode=exports.EnumCountryCode||(exports.EnumCountryCode={}),EnumCountryCode.CH="CH",EnumCountryCode.DE="DE",EnumCountryCode.FR="FR",EnumCountryCode.IT="IT",EnumCountryCode.NL="NL",EnumCountryCode.PT="PT",EnumCountryCode.US="US",exports.EnumLocale=void 0,EnumLocale=exports.EnumLocale||(exports.EnumLocale={}),EnumLocale.ch_de="ch_DE",EnumLocale.ch_fr="ch_FR",EnumLocale.ch_it="ch_it",EnumLocale.de_DE="de_DE",EnumLocale.it_IT="it_IT",EnumLocale.fr_FR="fr_FR",EnumLocale.pt_PT="pt_PT",EnumLocale.en_US="en_US",exports.EnumTimezone=void 0,EnumTimezone=exports.EnumTimezone||(exports.EnumTimezone={}),EnumTimezone.EuropeBerlin="Europe/Berlin",EnumTimezone.EuropeLondon="Europe/London",EnumTimezone.EuropeSofia="Europe/Sofia",EnumTimezone.EuropeZurich="Europe/Zurich",EnumTimezone.UTC="UTC",exports.EnumServiceProviderType=void 0,EnumServiceProviderType=exports.EnumServiceProviderType||(exports.EnumServiceProviderType={}),EnumServiceProviderType.propertyManager="property-manager",EnumServiceProviderType.craftspeople="craftspeople",exports.EnumCommunicationMethodType=void 0,EnumCommunicationMethodType=exports.EnumCommunicationMethodType||(exports.EnumCommunicationMethodType={}),EnumCommunicationMethodType.email="email",exports.EnumInputChannel=void 0,EnumInputChannel=exports.EnumInputChannel||(exports.EnumInputChannel={}),EnumInputChannel.APP="app",EnumInputChannel.COCKPIT="cockpit",EnumInputChannel.CRAFTSMEN="craftsmen",EnumInputChannel.EMAIL="email",EnumInputChannel.PHONE="phone",EnumInputChannel.WHATS_APP="whats_app",exports.EnumLookupUserType=void 0,EnumLookupUserType=exports.EnumLookupUserType||(exports.EnumLookupUserType={}),EnumLookupUserType.agent="agent",EnumLookupUserType.tenant="tenant",exports.createTokenStore=createTokenStore,exports.restClient=restClient}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allthings/sdk",
3
- "version": "5.0.3",
3
+ "version": "5.0.4",
4
4
  "description": "",
5
5
  "author": "Allthings GmbH",
6
6
  "maintainers": [
@@ -44,7 +44,7 @@
44
44
  "lint:tslint": "tslint -p tsconfig.json -t stylish",
45
45
  "lint:tsc": "tsc --noEmit --pretty",
46
46
  "prebuild": "npm run clean",
47
- "build": "tsc -d && cp package.json dist/ && rollup -c && rm dist/package.json",
47
+ "build": "tsc -d && cp package.json dist/ && rollup -c --bundleConfigAsCjs && rm dist/package.json",
48
48
  "dev": "tsc -w",
49
49
  "prepare": "husky install",
50
50
  "prepublishOnly": "npm run build",
@@ -63,24 +63,24 @@
63
63
  },
64
64
  "devDependencies": {
65
65
  "@allthings/tslint-preset": "2.0.0",
66
- "@commitlint/cli": "17.5.1",
67
- "@commitlint/config-conventional": "17.4.4",
66
+ "@commitlint/cli": "17.6.1",
67
+ "@commitlint/config-conventional": "17.6.1",
68
68
  "@types/form-data": "2.5.0",
69
69
  "@types/jest": "26.0.24",
70
- "@types/node": "18.15.11",
70
+ "@types/node": "18.16.3",
71
71
  "@types/query-string": "6.3.0",
72
72
  "coveralls": "3.1.1",
73
73
  "form-data": "4.0.0",
74
74
  "husky": "8.0.3",
75
75
  "jest": "26.6.3",
76
76
  "jest-environment-jsdom": "26.6.2",
77
- "lint-staged": "13.2.1",
77
+ "lint-staged": "13.2.2",
78
78
  "nanoid": "3.3.6",
79
- "prettier": "2.8.7",
80
- "rimraf": "4.4.1",
81
- "rollup": "2.79.1",
79
+ "prettier": "2.8.8",
80
+ "rimraf": "5.0.0",
81
+ "rollup": "3.21.3",
82
82
  "rollup-plugin-commonjs": "10.1.0",
83
- "rollup-plugin-hashbang": "3.0.0",
83
+ "rollup-plugin-hashbang": "2.2.2",
84
84
  "rollup-plugin-json": "4.0.0",
85
85
  "@rollup/plugin-node-resolve": "15.0.2",
86
86
  "rollup-plugin-replace": "2.2.0",