@allthings/sdk 9.2.0-beta.2 → 9.2.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib.esm.js CHANGED
@@ -1,1348 +1 @@
1
- import Bottleneck from 'bottleneck';
2
-
3
- function createTokenStore(initialToken) {
4
- const token = new Map(Object.entries(initialToken || {}));
5
- return {
6
- get: (key) => token.get(key),
7
- reset: () => token.clear(),
8
- set: (update) => Object.entries(update).forEach(([key, value]) => token.set(key, value)),
9
- };
10
- }
11
-
12
- const version = "9.2.0-beta.2";
13
-
14
- const REST_API_URL = 'https://api.allthings.me';
15
- const OAUTH_URL = 'https://accounts.allthings.me';
16
- const QUEUE_CONCURRENCY = undefined;
17
- const QUEUE_DELAY = 0;
18
- const QUEUE_RESERVOIR = 30;
19
- const QUEUE_RESERVOIR_REFILL_INTERVAL = 166;
20
- const REQUEST_BACK_OFF_INTERVAL = 200;
21
- const REQUEST_MAX_RETRIES = 50;
22
- const DEFAULT_API_WRAPPER_OPTIONS = {
23
- apiUrl: process.env.ALLTHINGS_REST_API_URL || REST_API_URL,
24
- clientId: process.env.ALLTHINGS_OAUTH_CLIENT_ID,
25
- clientSecret: process.env.ALLTHINGS_OAUTH_CLIENT_SECRET,
26
- oauthUrl: process.env.ALLTHINGS_OAUTH_URL || OAUTH_URL,
27
- password: process.env.ALLTHINGS_OAUTH_PASSWORD,
28
- requestBackOffInterval: REQUEST_BACK_OFF_INTERVAL,
29
- requestMaxRetries: REQUEST_MAX_RETRIES,
30
- scope: 'user:profile',
31
- username: process.env.ALLTHINGS_OAUTH_USERNAME,
32
- };
33
- const USER_AGENT = `Allthings Node SDK REST Client/${version}`;
34
-
35
- function buildQueryString(params) {
36
- const usp = new URLSearchParams();
37
- for (const [key, value] of Object.entries(params).sort(([a], [b]) => a.localeCompare(b))) {
38
- if (value != null && value !== '') {
39
- usp.append(key, String(value));
40
- }
41
- }
42
- return usp.toString();
43
- }
44
- function parseQueryString(query) {
45
- const cleaned = query.startsWith('#') ? query.slice(1) : query;
46
- return Object.fromEntries(new URLSearchParams(cleaned));
47
- }
48
-
49
- const RESPONSE_TYPE$1 = 'code';
50
- const GRANT_TYPE$3 = 'authorization_code';
51
- const castToAuthorizationRequestParameters$1 = (parameters) => {
52
- const { redirectUri, clientId, scope, state } = parameters;
53
- if (!clientId) {
54
- throw new Error('Missing required "clientId" parameter to perform authorization code grant redirect');
55
- }
56
- if (!redirectUri) {
57
- throw new Error('Missing required "redirectUri" parameter to perform authorization code grant redirect');
58
- }
59
- return {
60
- client_id: clientId,
61
- redirect_uri: redirectUri,
62
- response_type: RESPONSE_TYPE$1,
63
- ...(scope ? { scope } : {}),
64
- ...(state ? { state } : {}),
65
- };
66
- };
67
- const isEligibleForClientRedirect$1 = (parameters) => {
68
- try {
69
- return !!castToAuthorizationRequestParameters$1(parameters);
70
- }
71
- catch {
72
- return false;
73
- }
74
- };
75
- const getRedirectUrl$1 = (parameters) => `${parameters.oauthUrl}/oauth/authorize?${buildQueryString(castToAuthorizationRequestParameters$1(parameters))}`;
76
- const castToTokenRequestParameters$2 = (parameters) => {
77
- const { authorizationCode, redirectUri, clientId, clientSecret } = parameters;
78
- if (!clientId) {
79
- throw new Error('Missing required "clientId" parameter to perform authorization code grant');
80
- }
81
- if (!redirectUri) {
82
- throw new Error('Missing required "redirectUri" parameter to perform authorization code grant');
83
- }
84
- if (!authorizationCode) {
85
- throw new Error('Missing required "authorizationCode" parameter to perform authorization code grant');
86
- }
87
- return {
88
- client_id: clientId,
89
- code: authorizationCode,
90
- grant_type: GRANT_TYPE$3,
91
- redirect_uri: redirectUri,
92
- ...(clientSecret ? { client_secret: clientSecret } : {}),
93
- };
94
- };
95
- const isEligible$3 = (parameters) => {
96
- try {
97
- return !!castToTokenRequestParameters$2(parameters);
98
- }
99
- catch {
100
- return false;
101
- }
102
- };
103
- const requestToken$3 = (tokenRequester, parameters) => tokenRequester(castToTokenRequestParameters$2(parameters));
104
-
105
- const SUBSCRIPTIONS = process.env.DEBUG?.split(',').map((item) => item.trim()) || [];
106
- function makeLogger(name) {
107
- return ['log', 'info', 'warn', 'error'].reduce((logger, type) => ({
108
- ...logger,
109
- [type]: function log(...logs) {
110
- if (SUBSCRIPTIONS.includes('*') ||
111
- SUBSCRIPTIONS.includes(name) ||
112
- SUBSCRIPTIONS.includes(name.toLocaleLowerCase())) {
113
- console[type](`${name}:`, ...logs);
114
- }
115
- return true;
116
- },
117
- }), {});
118
- }
119
-
120
- const logger = makeLogger('OAuth Token Request');
121
- const makeFetchTokenRequester = (url) => async (parameters) => {
122
- try {
123
- const response = await fetch(url, {
124
- body: buildQueryString(parameters),
125
- cache: 'no-cache',
126
- credentials: 'omit',
127
- headers: {
128
- 'Content-Type': 'application/x-www-form-urlencoded',
129
- accept: 'application/json',
130
- 'user-agent': USER_AGENT,
131
- },
132
- method: 'POST',
133
- mode: 'cors',
134
- });
135
- if (response.status !== 200) {
136
- throw response;
137
- }
138
- const { access_token: newAccessToken, refresh_token: newRefreshToken, expires_in: expiresIn, } = await response.json();
139
- return {
140
- accessToken: newAccessToken,
141
- expiresIn,
142
- refreshToken: newRefreshToken,
143
- };
144
- }
145
- catch (error) {
146
- if (!(error instanceof Response)) {
147
- throw error;
148
- }
149
- const errorName = `HTTP ${error.status} — ${error.statusText}`;
150
- logger.error(errorName, error);
151
- throw new Error(`HTTP ${error.status} — ${error.statusText}. Could not get token.`);
152
- }
153
- };
154
-
155
- const GRANT_TYPE$2 = 'refresh_token';
156
- const castToTokenRequestParameters$1 = (parameters) => {
157
- const { clientId, clientSecret, refreshToken, scope } = parameters;
158
- if (!clientId) {
159
- throw new Error('Missing required "clientId" parameter to perform refresh token grant');
160
- }
161
- if (!refreshToken) {
162
- throw new Error('Missing required "refreshToken" parameter to perform refresh token grant');
163
- }
164
- return {
165
- client_id: clientId,
166
- grant_type: GRANT_TYPE$2,
167
- refresh_token: refreshToken,
168
- ...(clientSecret ? { client_secret: clientSecret } : {}),
169
- ...(scope ? { scope } : {}),
170
- };
171
- };
172
- const isEligible$2 = (parameters) => {
173
- try {
174
- return !!castToTokenRequestParameters$1(parameters);
175
- }
176
- catch {
177
- return false;
178
- }
179
- };
180
- const requestToken$2 = (tokenRequester, parameters) => tokenRequester(castToTokenRequestParameters$1(parameters));
181
-
182
- async function requestAndSaveToStore(requester, tokenStore) {
183
- const response = await requester();
184
- tokenStore.set(response);
185
- return response;
186
- }
187
-
188
- const partial = (function_, ...partialArguments) => (...arguments_) => function_(...partialArguments, ...arguments_);
189
- async function until(predicate, transformer, initialValue, iterationCount = 0) {
190
- const transformed = await transformer(initialValue, iterationCount);
191
- return (await predicate(transformed, iterationCount))
192
- ? transformed
193
- : until(predicate, transformer, transformed, iterationCount + 1);
194
- }
195
- function clearIntervalFunction(intervalId) {
196
- clearInterval(intervalId);
197
- return true;
198
- }
199
-
200
- function pseudoRandomString(length = 16) {
201
- let token = '';
202
- while (token.length < length) {
203
- token += Math.random().toString(36).slice(2);
204
- }
205
- return token.slice(0, Math.max(0, length));
206
- }
207
-
208
- async function del(request, method, body, returnRawResultObject, headers) {
209
- return request('delete', method, { body, headers }, returnRawResultObject);
210
- }
211
-
212
- async function get(request, method, query, returnRawResultObject, headers) {
213
- return request('get', method, { headers, query }, returnRawResultObject);
214
- }
215
-
216
- var EnumGender;
217
- (function (EnumGender) {
218
- EnumGender["female"] = "female";
219
- EnumGender["male"] = "male";
220
- })(EnumGender || (EnumGender = {}));
221
- var EnumUserType;
222
- (function (EnumUserType) {
223
- EnumUserType["allthingsUser"] = "allthings_user";
224
- EnumUserType["allthingsContent"] = "allthings_content";
225
- EnumUserType["customer"] = "customer";
226
- EnumUserType["demoContent"] = "demo_content";
227
- EnumUserType["demoPublic"] = "demo_public";
228
- EnumUserType["partner"] = "partner";
229
- })(EnumUserType || (EnumUserType = {}));
230
- var EnumCommunicationPreferenceChannel;
231
- (function (EnumCommunicationPreferenceChannel) {
232
- EnumCommunicationPreferenceChannel["push"] = "push";
233
- EnumCommunicationPreferenceChannel["email"] = "email";
234
- })(EnumCommunicationPreferenceChannel || (EnumCommunicationPreferenceChannel = {}));
235
- var EnumUserPermissionRole;
236
- (function (EnumUserPermissionRole) {
237
- EnumUserPermissionRole["appAdmin"] = "app-admin";
238
- EnumUserPermissionRole["appOwner"] = "app-owner";
239
- EnumUserPermissionRole["articlesAgent"] = "articles-agent";
240
- EnumUserPermissionRole["articlesViewOnly"] = "articles-view-only";
241
- EnumUserPermissionRole["bookableAssetAgent"] = "bookable-asset-agent";
242
- EnumUserPermissionRole["bookingAgent"] = "booking-agent";
243
- EnumUserPermissionRole["cockpitManager"] = "cockpit-manager";
244
- EnumUserPermissionRole["dataConnectorAdmin"] = "data-connector-admin";
245
- EnumUserPermissionRole["documentAdmin"] = "doc-admin";
246
- EnumUserPermissionRole["externalAgent"] = "external-agent";
247
- EnumUserPermissionRole["globalOrgAdmin"] = "global-org-admin";
248
- EnumUserPermissionRole["globalUserAdmin"] = "global-user-admin";
249
- EnumUserPermissionRole["orgAdmin"] = "org-admin";
250
- EnumUserPermissionRole["orgTeamManager"] = "org-team-manager";
251
- EnumUserPermissionRole["pinboardAgent"] = "pinboard-agent";
252
- EnumUserPermissionRole["platformOwner"] = "platform-owner";
253
- EnumUserPermissionRole["qa"] = "qa";
254
- EnumUserPermissionRole["serviceCenterAgent"] = "service-center-agent";
255
- EnumUserPermissionRole["serviceCenterManager"] = "service-center-manager";
256
- EnumUserPermissionRole["setup"] = "setup";
257
- EnumUserPermissionRole["tenantManager"] = "tenant-manager";
258
- })(EnumUserPermissionRole || (EnumUserPermissionRole = {}));
259
- var EnumUserPermissionObjectType;
260
- (function (EnumUserPermissionObjectType) {
261
- EnumUserPermissionObjectType["app"] = "App";
262
- EnumUserPermissionObjectType["group"] = "Group";
263
- EnumUserPermissionObjectType["property"] = "Property";
264
- EnumUserPermissionObjectType["unit"] = "Unit";
265
- })(EnumUserPermissionObjectType || (EnumUserPermissionObjectType = {}));
266
- const remapUserResult = (user) => {
267
- const { tenantIDs: tenantIds, ...result } = user;
268
- return { ...result, tenantIds };
269
- };
270
- const remapEmbeddedUser = (embedded) => embedded.users ? embedded.users.map(remapUserResult) : [];
271
- async function userCreate(client, appId, username, data) {
272
- return client.post('/v1/users', {
273
- ...data,
274
- creationContext: appId,
275
- username,
276
- });
277
- }
278
- async function getUsers(client, page = 1, limit = -1, filter = {}) {
279
- const { _embedded: { items: users }, total, } = await client.get('/v1/users', {
280
- filter: JSON.stringify(filter),
281
- limit,
282
- page,
283
- });
284
- return { _embedded: { items: users.map(remapUserResult) }, total };
285
- }
286
- async function getCurrentUser(client) {
287
- return remapUserResult(await client.get('/v1/me'));
288
- }
289
- async function userGetById(client, userId) {
290
- return remapUserResult(await client.get(`/v1/users/${userId}`));
291
- }
292
- async function userUpdateById(client, userId, data) {
293
- const { tenantIds: tenantIDs, ...rest } = data;
294
- return remapUserResult(await client.patch(`/v1/users/${userId}`, { ...rest, tenantIDs }));
295
- }
296
- async function userCreatePermission(client, userId, data) {
297
- const { objectId: objectID, ...rest } = data;
298
- const { objectID: resultObjectId, ...result } = await client.post(`/v1/users/${userId}/permissions`, {
299
- ...rest,
300
- objectID,
301
- });
302
- return {
303
- ...result,
304
- objectId: resultObjectId,
305
- };
306
- }
307
- async function userCreatePermissionBatch(client, userId, permissions) {
308
- const { objectId, objectType, roles, startDate, endDate } = permissions;
309
- const batch = {
310
- batch: roles.map((role) => ({
311
- endDate: endDate?.toISOString(),
312
- objectID: objectId,
313
- objectType,
314
- restrictions: [],
315
- role,
316
- startDate: startDate?.toISOString(),
317
- })),
318
- };
319
- return !(await client.post(`/v1/users/${userId}/permissions`, batch));
320
- }
321
- async function userGetPermissions(client, userId) {
322
- const { _embedded: { items: permissions }, } = await client.get(`/v1/users/${userId}/roles?limit=-1`);
323
- return permissions.map(({ objectID: objectId, ...result }) => ({
324
- ...result,
325
- objectId,
326
- }));
327
- }
328
- async function userDeletePermission(client, permissionId) {
329
- return !(await client.delete(`/v1/permissions/${permissionId}`));
330
- }
331
- async function userGetUtilisationPeriods(client, userId) {
332
- const { _embedded: { items: utilisationPeriods }, } = await client.get(`/v1/users/${userId}/utilisation-periods`);
333
- return utilisationPeriods;
334
- }
335
- async function userCheckInToUtilisationPeriod(client, userId, utilisationPeriodId) {
336
- const { email: userEmail } = await client.userGetById(userId);
337
- return client.utilisationPeriodCheckInUser(utilisationPeriodId, {
338
- email: userEmail,
339
- });
340
- }
341
- async function userGetByEmail(client, email, page = 1, limit = 1000) {
342
- return client.getUsers(page, limit, { email });
343
- }
344
- async function userChangePassword(client, userId, currentPassword, newPassword) {
345
- return !(await client.put(`/v1/users/${userId}/password`, {
346
- currentPassword,
347
- plainPassword: newPassword,
348
- }));
349
- }
350
-
351
- async function agentCreate(client, appId, propertyManagerId, username, data, sendInvitation, externalAgentCompany) {
352
- const user = await client.userCreate(appId, username, {
353
- ...data,
354
- type: EnumUserType.customer,
355
- });
356
- const manager = await client.post(`/v1/property-managers/${propertyManagerId}/users`, {
357
- userID: user.id,
358
- ...(externalAgentCompany && { externalAgentCompany }),
359
- });
360
- return (!((typeof sendInvitation !== 'undefined' ? sendInvitation : true) &&
361
- (await client.post(`/v1/users/${user.id}/invitations`))) && {
362
- ...user,
363
- ...manager,
364
- });
365
- }
366
- async function agentCreatePermissions(client, agentId, objectId, objectType, permissions, startDate, endDate) {
367
- return client.userCreatePermissionBatch(agentId, {
368
- endDate,
369
- objectId,
370
- objectType,
371
- restrictions: [],
372
- roles: permissions,
373
- startDate,
374
- });
375
- }
376
-
377
- async function appCreate(client, userId, data) {
378
- return client.post(`/v1/users/${userId}/apps`, {
379
- availableLocales: { '0': 'de_DE' },
380
- ...data,
381
- siteUrl: data.siteUrl.replace('_', ''),
382
- });
383
- }
384
- async function appGetById(client, appId) {
385
- return client.get(`/v1/apps/${appId}`);
386
- }
387
-
388
- async function bookingGetById(client, bookingId) {
389
- return client.get(`/v1/bookings/${bookingId}`);
390
- }
391
- async function bookingUpdateById(client, bookingId, data) {
392
- return client.patch(`/v1/bookings/${bookingId}`, data);
393
- }
394
-
395
- async function bucketGet(client, bucketId) {
396
- return client.get(`/v1/buckets/${bucketId}`);
397
- }
398
- async function bucketCreate(client, data) {
399
- return client.post('/v1/buckets', {
400
- channels: data.channels,
401
- name: data.name,
402
- });
403
- }
404
- async function bucketAddFile(client, bucketId, fileId) {
405
- return ((await client.post(`/v1/buckets/${bucketId}/files`, {
406
- id: fileId,
407
- })) === '');
408
- }
409
- async function bucketRemoveFile(client, bucketId, fileId) {
410
- return (await client.delete(`/v1/buckets/${bucketId}/files/${fileId}`)) === '';
411
- }
412
- async function bucketRemoveFilesInPath(client, bucketId, data) {
413
- return ((await client.delete(`/v1/buckets/${bucketId}/files`, {
414
- folder: data.path,
415
- })) === '');
416
- }
417
-
418
- const createManyFiles = async (attachments, apiClient) => {
419
- const responses = await Promise.all(attachments.map(async (attachment) => {
420
- try {
421
- const result = await apiClient.fileCreate({
422
- file: attachment.content,
423
- name: attachment.filename,
424
- });
425
- return result;
426
- }
427
- catch (error) {
428
- return error instanceof Error ? error : new Error(String(error));
429
- }
430
- }));
431
- return responses;
432
- };
433
- async function createManyFilesSorted(files, client) {
434
- const result = await createManyFiles(files, client);
435
- return {
436
- error: result.filter((item) => item instanceof Error),
437
- success: result
438
- .filter((item) => !(item instanceof Error))
439
- .map((item) => item.id),
440
- };
441
- }
442
-
443
- async function conversationGetById(client, conversationId) {
444
- return client.get(`/v1/conversations/${conversationId}`);
445
- }
446
- async function conversationCreateMessage(client, conversationId, messageData) {
447
- const url = `/v1/conversations/${conversationId}/messages`;
448
- const payload = messageData.attachments?.length
449
- ? {
450
- content: {
451
- description: messageData.body,
452
- files: (await createManyFilesSorted(messageData.attachments, client))
453
- .success,
454
- },
455
- createdBy: messageData.createdBy,
456
- inputChannel: messageData.inputChannel,
457
- internal: false,
458
- type: 'file',
459
- }
460
- : {
461
- content: {
462
- content: messageData.body,
463
- },
464
- createdBy: messageData.createdBy,
465
- inputChannel: messageData.inputChannel,
466
- type: 'text',
467
- };
468
- return client.post(url, payload);
469
- }
470
-
471
- async function fileCreate(client, data) {
472
- return client.post('/v1/files', {
473
- formData: {
474
- file: [data.file, data.name],
475
- path: data.path || '',
476
- },
477
- });
478
- }
479
- async function fileDelete(client, fileId) {
480
- return (await client.delete(`/v1/files/${fileId}`)) === '';
481
- }
482
-
483
- async function groupCreate(client, propertyId, data) {
484
- const { propertyManagerId, ...rest } = data;
485
- return client.post(`/v1/properties/${propertyId}/groups`, {
486
- ...rest,
487
- propertyManagerID: propertyManagerId,
488
- });
489
- }
490
- async function groupGetById(client, groupId) {
491
- const { propertyManagerID: propertyManagerId, ...result } = await client.get(`/v1/groups/${groupId}`);
492
- return { ...result, propertyManagerId };
493
- }
494
- async function groupUpdateById(client, groupId, data) {
495
- return client.patch(`/v1/groups/${groupId}`, data);
496
- }
497
- async function getGroups(client, page = 1, limit = -1, filter = {}) {
498
- const { _embedded: { items: groups }, total, } = await client.get('/v1/groups', {
499
- filter: JSON.stringify(filter),
500
- limit,
501
- page,
502
- });
503
- return { _embedded: { items: groups }, total };
504
- }
505
-
506
- async function lookupIds(client, appId, data) {
507
- const url = data.dataSource
508
- ? `/v1/id-lookup/${appId}/${data.resource}/${data.dataSource}`
509
- : `/v1/id-lookup/${appId}/${data.resource}`;
510
- return client.post(url, {
511
- externalIds: typeof data.externalIds === 'string'
512
- ? [data.externalIds]
513
- : data.externalIds,
514
- ...(data.parentId ? { parentId: data.parentId } : {}),
515
- ...(data.userType ? { userType: data.userType } : {}),
516
- });
517
- }
518
-
519
- function stringToDate(s) {
520
- return new Date(Date.parse(s));
521
- }
522
- function dateToString(d) {
523
- return d.toISOString();
524
- }
525
-
526
- var EnumNotificationCategory;
527
- (function (EnumNotificationCategory) {
528
- EnumNotificationCategory["events"] = "events";
529
- EnumNotificationCategory["hintsAndTips"] = "hints-and-tips";
530
- EnumNotificationCategory["lostAndFound"] = "lost-and-found";
531
- EnumNotificationCategory["localDeals"] = "local-deals";
532
- EnumNotificationCategory["localEvents"] = "local-events";
533
- EnumNotificationCategory["miscellaneous"] = "miscellaneous";
534
- EnumNotificationCategory["deals"] = "deals";
535
- EnumNotificationCategory["messages"] = "messages";
536
- EnumNotificationCategory["adminMessages"] = "admin-messages";
537
- EnumNotificationCategory["newThingsToGive"] = "new-things-to-give";
538
- EnumNotificationCategory["newThingsForSale"] = "new-things-for-sale";
539
- EnumNotificationCategory["surveys"] = "surveys";
540
- EnumNotificationCategory["supportOffer"] = "support-offer";
541
- EnumNotificationCategory["supportRequest"] = "support-request";
542
- EnumNotificationCategory["sustainability"] = "sustainability";
543
- EnumNotificationCategory["localServices"] = "local-services";
544
- EnumNotificationCategory["services"] = "services";
545
- EnumNotificationCategory["ticketDigestEmail"] = "ticket-digest-email";
546
- EnumNotificationCategory["appDigestEmail"] = "app-digest-email";
547
- EnumNotificationCategory["newFile"] = "new-file";
548
- })(EnumNotificationCategory || (EnumNotificationCategory = {}));
549
- var EnumNotificationType;
550
- (function (EnumNotificationType) {
551
- EnumNotificationType["clipboardThing"] = "clipboard-thing";
552
- EnumNotificationType["comment"] = "comment";
553
- EnumNotificationType["communityArticle"] = "community-article";
554
- EnumNotificationType["newFile"] = "new-file";
555
- EnumNotificationType["ticketComment"] = "ticket-comment";
556
- EnumNotificationType["welcomeNotification"] = "welcome-notification";
557
- })(EnumNotificationType || (EnumNotificationType = {}));
558
- function remapNotificationResult({ createdAt, objectID, referencedObjectID, ...restNotification }) {
559
- return {
560
- createdAt: stringToDate(createdAt),
561
- objectId: objectID,
562
- referencedObjectId: referencedObjectID,
563
- ...restNotification,
564
- };
565
- }
566
- async function notificationsGetByUser(client, userId, page = 1, limit = -1) {
567
- const { _embedded: { items: notifications }, total, metaData, } = await client.get(`/v1/users/${userId}/notifications?page=${page}&limit=${limit}`);
568
- return {
569
- _embedded: { items: notifications.map(remapNotificationResult) },
570
- metaData,
571
- total,
572
- };
573
- }
574
- async function notificationsUpdateReadByUser(client, userId, lastReadAt = new Date()) {
575
- return client.patch(`/v1/users/${userId}/notifications`, {
576
- lastReadAt: dateToString(lastReadAt),
577
- });
578
- }
579
- async function notificationUpdateRead(client, notificationId) {
580
- return remapNotificationResult(await client.patch(`/v1/notifications/${notificationId}`, { read: true }));
581
- }
582
-
583
- function remapKeys(input, mapFunction) {
584
- return Object.entries(input).reduce((accumulator, entry) => ({
585
- ...accumulator,
586
- [mapFunction(entry[0])]: entry[1],
587
- }), {});
588
- }
589
-
590
- function camelCaseToDash(input) {
591
- return input.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`);
592
- }
593
- function dashCaseToCamel(input) {
594
- return input.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
595
- }
596
-
597
- var EnumNotificationSettingsValue;
598
- (function (EnumNotificationSettingsValue) {
599
- EnumNotificationSettingsValue["never"] = "never";
600
- EnumNotificationSettingsValue["immediately"] = "immediately";
601
- EnumNotificationSettingsValue["daily"] = "daily";
602
- EnumNotificationSettingsValue["weekly"] = "weekly";
603
- EnumNotificationSettingsValue["biweekly"] = "biweekly";
604
- EnumNotificationSettingsValue["monthly"] = "monthly";
605
- })(EnumNotificationSettingsValue || (EnumNotificationSettingsValue = {}));
606
- async function notificationSettingsUpdateByUser(client, userId, data) {
607
- const result = await client.patch(`/v1/users/${userId}/notification-settings`, { notificationSettings: remapKeys(data, camelCaseToDash) });
608
- return remapKeys(result, dashCaseToCamel);
609
- }
610
- async function notificationSettingsResetByUser(client, userId) {
611
- const result = await client.delete(`/v1/users/${userId}/notification-settings`);
612
- return remapKeys(result, dashCaseToCamel);
613
- }
614
-
615
- async function propertyCreate(client, appId, data) {
616
- return client.post(`/v1/apps/${appId}/properties`, data);
617
- }
618
- async function propertyGetById(client, propertyId) {
619
- return client.get(`/v1/properties/${propertyId}`);
620
- }
621
- async function propertyUpdateById(client, propertyId, data) {
622
- return client.patch(`/v1/properties/${propertyId}`, data);
623
- }
624
- async function getProperties(client, page = 1, limit = -1, filter = {}) {
625
- const { _embedded: { items: properties }, total, } = await client.get('/v1/properties', {
626
- filter: JSON.stringify(filter),
627
- limit,
628
- page,
629
- });
630
- return { _embedded: { items: properties }, total };
631
- }
632
-
633
- const remapRegistationCodeResult = (registrationCode) => {
634
- const { tenantID: externalId, ...result } = registrationCode;
635
- return { ...result, externalId };
636
- };
637
- async function registrationCodeCreate(client, code, utilisationPeriods, options = { permanent: false }) {
638
- const { externalId, ...moreOptions } = options;
639
- return remapRegistationCodeResult(await client.post('/v1/registration-codes', {
640
- code,
641
- utilisationPeriods: typeof utilisationPeriods === 'string'
642
- ? [utilisationPeriods]
643
- : utilisationPeriods,
644
- ...(externalId ? { externalId, tenantID: externalId } : {}),
645
- ...moreOptions,
646
- }));
647
- }
648
- async function registrationCodeUpdateById(client, registrationCodeId, data) {
649
- return remapRegistationCodeResult(await client.patch(`/v1/registration-codes/${registrationCodeId}`, data));
650
- }
651
- async function registrationCodeGetById(client, registrationCodeId) {
652
- return remapRegistationCodeResult(await client.get(`/v1/invitations/${registrationCodeId}`));
653
- }
654
- async function registrationCodeDelete(client, registrationCodeId) {
655
- return (await client.delete(`/v1/invitations/${registrationCodeId}`)) === '';
656
- }
657
-
658
- async function serviceProviderCreate(client, data) {
659
- return client.post('/v1/service-providers', data);
660
- }
661
- async function serviceProviderGetById(client, serviceProviderId) {
662
- return client.get(`/v1/service-providers/${serviceProviderId}`);
663
- }
664
- async function serviceProviderUpdateById(client, serviceProviderId, data) {
665
- return client.patch(`/v1/service-providers/${serviceProviderId}`, data);
666
- }
667
-
668
- var ETicketStatus;
669
- (function (ETicketStatus) {
670
- ETicketStatus["CLOSED"] = "closed";
671
- ETicketStatus["WAITING_FOR_AGENT"] = "waiting-for-agent";
672
- ETicketStatus["WAITING_FOR_CUSTOMER"] = "waiting-for-customer";
673
- ETicketStatus["WAITING_FOR_EXTERNAL"] = "waiting-for-external";
674
- })(ETicketStatus || (ETicketStatus = {}));
675
- var ETrafficLightColor;
676
- (function (ETrafficLightColor) {
677
- ETrafficLightColor["GREEN"] = "green";
678
- ETrafficLightColor["RED"] = "red";
679
- ETrafficLightColor["YELLOW"] = "yellow";
680
- })(ETrafficLightColor || (ETrafficLightColor = {}));
681
- async function ticketGetById(client, ticketId) {
682
- return client.get(`/v1/tickets/${ticketId}`);
683
- }
684
- async function ticketCreateOnUser(client, userId, utilisationPeriodId, payload) {
685
- return client.post(`/v1/users/${userId}/tickets`, {
686
- ...payload,
687
- files: payload.files
688
- ? (await createManyFilesSorted(payload.files, client)).success
689
- : [],
690
- utilisationPeriod: utilisationPeriodId,
691
- });
692
- }
693
- async function ticketCreateOnServiceProvider(client, serviceProviderId, payload) {
694
- return client.post(`/v1/property-managers/${serviceProviderId}/tickets`, {
695
- ...payload,
696
- files: payload.files
697
- ? (await createManyFilesSorted(payload.files, client)).success
698
- : [],
699
- });
700
- }
701
-
702
- var EnumUnitObjectType;
703
- (function (EnumUnitObjectType) {
704
- EnumUnitObjectType["adjoiningRoom"] = "adjoining-room";
705
- EnumUnitObjectType["advertisingSpace"] = "advertising-space";
706
- EnumUnitObjectType["aerial"] = "aerial";
707
- EnumUnitObjectType["apartmentBuilding"] = "apartment-building";
708
- EnumUnitObjectType["atm"] = "atm";
709
- EnumUnitObjectType["atmRoom"] = "atm-room";
710
- EnumUnitObjectType["attic"] = "attic";
711
- EnumUnitObjectType["atticFlat"] = "attic-flat";
712
- EnumUnitObjectType["bank"] = "bank";
713
- EnumUnitObjectType["basment"] = "basment";
714
- EnumUnitObjectType["bikeShed"] = "bike-shed";
715
- EnumUnitObjectType["buildingLaw"] = "building-law";
716
- EnumUnitObjectType["cafeteria"] = "cafeteria";
717
- EnumUnitObjectType["caretakerRoom"] = "caretaker-room";
718
- EnumUnitObjectType["carport"] = "carport";
719
- EnumUnitObjectType["cellar"] = "cellar";
720
- EnumUnitObjectType["commercialProperty"] = "commercial-property";
721
- EnumUnitObjectType["commonRoom"] = "common-room";
722
- EnumUnitObjectType["deliveryZone"] = "delivery-zone";
723
- EnumUnitObjectType["diverse"] = "diverse";
724
- EnumUnitObjectType["doubleParkingSpace"] = "double-parking-space";
725
- EnumUnitObjectType["engineeringRoom"] = "engineering-room";
726
- EnumUnitObjectType["entertainment"] = "entertainment";
727
- EnumUnitObjectType["environment"] = "environment";
728
- EnumUnitObjectType["estate"] = "estate";
729
- EnumUnitObjectType["fillingStation"] = "filling-station";
730
- EnumUnitObjectType["fitnessCenter"] = "fitness-center";
731
- EnumUnitObjectType["flat"] = "flat";
732
- EnumUnitObjectType["freeZone"] = "free-zone";
733
- EnumUnitObjectType["garage"] = "garage";
734
- EnumUnitObjectType["garden"] = "garden";
735
- EnumUnitObjectType["gardenFlat"] = "garden-flat";
736
- EnumUnitObjectType["heatingFacilities"] = "heating-facilities";
737
- EnumUnitObjectType["hotel"] = "hotel";
738
- EnumUnitObjectType["incidentalRentalExpenses"] = "incidental-rental-expenses";
739
- EnumUnitObjectType["industry"] = "industry";
740
- EnumUnitObjectType["kiosk"] = "kiosk";
741
- EnumUnitObjectType["kitchen"] = "kitchen";
742
- EnumUnitObjectType["loft"] = "loft";
743
- EnumUnitObjectType["machine"] = "machine";
744
- EnumUnitObjectType["maisonette"] = "maisonette";
745
- EnumUnitObjectType["medicalPractice"] = "medical-practice";
746
- EnumUnitObjectType["mopedShed"] = "moped-shed";
747
- EnumUnitObjectType["motorcycleParkingSpace"] = "motorcycle-parking-space";
748
- EnumUnitObjectType["office"] = "office";
749
- EnumUnitObjectType["oneFamilyHouse"] = "one-family-house";
750
- EnumUnitObjectType["parkingBox"] = "parking-box";
751
- EnumUnitObjectType["parkingGarage"] = "parking-garage";
752
- EnumUnitObjectType["parkingSpace"] = "parking-space";
753
- EnumUnitObjectType["parkingSpaces"] = "parking-spaces";
754
- EnumUnitObjectType["penthouse"] = "penthouse";
755
- EnumUnitObjectType["productionPlant"] = "production-plant";
756
- EnumUnitObjectType["pub"] = "pub";
757
- EnumUnitObjectType["publicArea"] = "public-area";
758
- EnumUnitObjectType["restaurant"] = "restaurant";
759
- EnumUnitObjectType["retirementHome"] = "retirement-home";
760
- EnumUnitObjectType["salesFloor"] = "sales-floor";
761
- EnumUnitObjectType["school"] = "school";
762
- EnumUnitObjectType["shelter"] = "shelter";
763
- EnumUnitObjectType["storage"] = "storage";
764
- EnumUnitObjectType["store"] = "store";
765
- EnumUnitObjectType["storeroom"] = "storeroom";
766
- EnumUnitObjectType["studio"] = "studio";
767
- EnumUnitObjectType["terrace"] = "terrace";
768
- EnumUnitObjectType["toilets"] = "toilets";
769
- EnumUnitObjectType["utilityRoom"] = "utility-room";
770
- EnumUnitObjectType["variableParkingSpace"] = "variable-parking-space";
771
- EnumUnitObjectType["variableRoom"] = "variable-room";
772
- EnumUnitObjectType["visitorParkingSpace"] = "visitor-parking-space";
773
- EnumUnitObjectType["workshop"] = "workshop";
774
- })(EnumUnitObjectType || (EnumUnitObjectType = {}));
775
- var EnumUnitType;
776
- (function (EnumUnitType) {
777
- EnumUnitType["rented"] = "rented";
778
- EnumUnitType["owned"] = "owned";
779
- })(EnumUnitType || (EnumUnitType = {}));
780
- async function unitCreate(client, groupId, data) {
781
- return client.post(`/v1/groups/${groupId}/units`, data);
782
- }
783
- async function unitGetById(client, unitId) {
784
- return client.get(`/v1/units/${unitId}`);
785
- }
786
- async function unitUpdateById(client, unitId, data) {
787
- return client.patch(`/v1/units/${unitId}`, data);
788
- }
789
- async function getUnits(client, page = 1, limit = -1, filter = {}) {
790
- const { _embedded: { items: units }, total, } = await client.get('/v1/units', {
791
- filter: JSON.stringify(filter),
792
- limit,
793
- page,
794
- });
795
- return { _embedded: { items: units }, total };
796
- }
797
-
798
- var EnumUserRelationType;
799
- (function (EnumUserRelationType) {
800
- EnumUserRelationType["isResponsible"] = "is-responsible";
801
- })(EnumUserRelationType || (EnumUserRelationType = {}));
802
- async function userRelationCreate(client, userId, data) {
803
- return client.post(`/v1/users/${userId}/user-relations/${data.type}`, {
804
- ids: data.ids,
805
- level: data.level,
806
- readOnly: data.readOnly,
807
- role: data.role,
808
- });
809
- }
810
- async function userRelationDelete(client, userId, data) {
811
- return client.delete(`/v1/users/${userId}/user-relations/${data.type}`, {
812
- ids: data.ids,
813
- level: data.level,
814
- role: data.role,
815
- });
816
- }
817
- async function userRelationsGetByUser(client, userId) {
818
- return client.get(`/v1/users/${userId}/user-relations`);
819
- }
820
-
821
- var EnumUtilisationPeriodType;
822
- (function (EnumUtilisationPeriodType) {
823
- EnumUtilisationPeriodType["tenant"] = "tenant";
824
- EnumUtilisationPeriodType["ownership"] = "ownership";
825
- EnumUtilisationPeriodType["vacant"] = "vacant";
826
- })(EnumUtilisationPeriodType || (EnumUtilisationPeriodType = {}));
827
- async function utilisationPeriodCreate(client, unitId, data) {
828
- const { tenantIDs: tenantIds, _embedded, ...result } = await client.post(`/v1/units/${unitId}/utilisation-periods`, data);
829
- return {
830
- ...result,
831
- invitations: _embedded.invitations.map(remapRegistationCodeResult),
832
- tenantIds,
833
- users: remapEmbeddedUser(_embedded),
834
- };
835
- }
836
- async function utilisationPeriodGetById(client, utilisationPeriodId) {
837
- const { tenantIDs: tenantIds, _embedded, ...result } = await client.get(`/v1/utilisation-periods/${utilisationPeriodId}`);
838
- return {
839
- ...result,
840
- invitations: _embedded.invitations.map(remapRegistationCodeResult),
841
- tenantIds,
842
- users: remapEmbeddedUser(_embedded),
843
- };
844
- }
845
- async function utilisationPeriodUpdateById(client, utilisationPeriodId, data) {
846
- const { tenantIDs: tenantIds, _embedded, ...result } = await client.patch(`/v1/utilisation-periods/${utilisationPeriodId}`, data);
847
- return {
848
- ...result,
849
- invitations: _embedded.invitations.map(remapRegistationCodeResult),
850
- tenantIds,
851
- users: remapEmbeddedUser(_embedded),
852
- };
853
- }
854
- async function utilisationPeriodDelete(client, utilisationPeriodId) {
855
- return !(await client.delete(`/v1/utilisation-periods/${utilisationPeriodId}/soft`));
856
- }
857
- async function utilisationPeriodCheckInUser(client, utilisationPeriodId, data) {
858
- return ((await client.post(`/v1/utilisation-periods/${utilisationPeriodId}/users`, {
859
- email: data.email,
860
- })) && client.utilisationPeriodGetById(utilisationPeriodId));
861
- }
862
- async function utilisationPeriodCheckOutUser(client, utilisationPeriodId, userId) {
863
- return ((await client.delete(`/v1/utilisation-periods/${utilisationPeriodId}/users/${userId}`)) === '');
864
- }
865
- async function utilisationPeriodAddRegistrationCode(client, utilisationPeriodId, code, tenant, permanent = false) {
866
- return client.post(`/v1/utilisation-periods/${utilisationPeriodId}/registration-codes`, { code, permanent, tenant });
867
- }
868
-
869
- async function patch(request, method, body, returnRawResultObject, headers) {
870
- return request('patch', method, { body, headers }, returnRawResultObject);
871
- }
872
-
873
- async function post(request, method, body, returnRawResultObject, headers) {
874
- return request('post', method, { body, headers }, returnRawResultObject);
875
- }
876
-
877
- async function put(request, method, body, returnRawResultObject, headers) {
878
- return request('put', method, { body, headers }, returnRawResultObject);
879
- }
880
-
881
- const GRANT_TYPE$1 = 'client_credentials';
882
- const castClientOptionsToRequestParameters = (clientOptions) => {
883
- const { scope, clientId, clientSecret } = clientOptions;
884
- if (!clientId) {
885
- throw new Error('Missing required "clientId" parameter to perform client credentials grant');
886
- }
887
- if (!clientSecret) {
888
- throw new Error('Missing required "clientSecret" parameter to perform client credentials grant');
889
- }
890
- return {
891
- client_id: clientId,
892
- client_secret: clientSecret,
893
- grant_type: GRANT_TYPE$1,
894
- ...(scope ? { scope } : {}),
895
- };
896
- };
897
- const isEligible$1 = (clientOptions) => {
898
- try {
899
- return !!castClientOptionsToRequestParameters(clientOptions);
900
- }
901
- catch {
902
- return false;
903
- }
904
- };
905
- const requestToken$1 = (oauthTokenRequest, clientOptions) => oauthTokenRequest(castClientOptionsToRequestParameters(clientOptions));
906
-
907
- const RESPONSE_TYPE = 'token';
908
- const castToAuthorizationRequestParameters = (parameters) => {
909
- const { clientId, scope, state, redirectUri } = parameters;
910
- if (!clientId) {
911
- throw new Error('Missing required "clientId" parameter to perform implicit grant');
912
- }
913
- return {
914
- client_id: clientId,
915
- redirect_uri: redirectUri || window.location.href,
916
- response_type: RESPONSE_TYPE,
917
- ...(scope ? { scope } : {}),
918
- ...(state ? { state } : {}),
919
- };
920
- };
921
- const isEligibleForClientRedirect = (parameters) => {
922
- try {
923
- return !!castToAuthorizationRequestParameters(parameters);
924
- }
925
- catch {
926
- return false;
927
- }
928
- };
929
- const getRedirectUrl = (parameters) => `${parameters.oauthUrl}/oauth/authorize?${buildQueryString(castToAuthorizationRequestParameters(parameters))}`;
930
-
931
- const GRANT_TYPE = 'password';
932
- const castToTokenRequestParameters = (parameters) => {
933
- const { username, password, scope, clientId, clientSecret } = parameters;
934
- if (!clientId) {
935
- throw new Error('Missing required "clientId" parameter to perform password grant');
936
- }
937
- if (!username) {
938
- throw new Error('Missing required "username" parameter to perform password grant');
939
- }
940
- if (!password) {
941
- throw new Error('Missing required "password" parameter to perform password grant');
942
- }
943
- return {
944
- client_id: clientId,
945
- grant_type: GRANT_TYPE,
946
- password,
947
- username,
948
- ...(scope ? { scope } : {}),
949
- ...(clientSecret ? { client_secret: clientSecret } : {}),
950
- };
951
- };
952
- const isEligible = (parameters) => {
953
- try {
954
- return !!castToTokenRequestParameters(parameters);
955
- }
956
- catch {
957
- return false;
958
- }
959
- };
960
- const requestToken = (tokenRequester, parameters) => tokenRequester(castToTokenRequestParameters(parameters));
961
-
962
- async function maybeUpdateToken(oauthTokenStore, tokenFetcher, options, mustRefresh = false) {
963
- if (!mustRefresh && oauthTokenStore.get('accessToken')) {
964
- return;
965
- }
966
- const refreshOptions = {
967
- ...options,
968
- refreshToken: oauthTokenStore.get('refreshToken'),
969
- };
970
- if (isEligible$2(refreshOptions)) {
971
- return oauthTokenStore.set(await requestToken$2(tokenFetcher, refreshOptions));
972
- }
973
- if (isEligible(options)) {
974
- return oauthTokenStore.set(await requestToken(tokenFetcher, options));
975
- }
976
- if (typeof window !== 'undefined' && options.implicit) {
977
- const parsedLocationHash = parseQueryString(window.location.hash);
978
- const accessToken = parsedLocationHash.access_token;
979
- if (accessToken) {
980
- window.history.replaceState({}, '', window.location.href.split('#')[0]);
981
- return oauthTokenStore.set({ accessToken });
982
- }
983
- if (isEligibleForClientRedirect(options)) {
984
- window.location.href = getRedirectUrl(options);
985
- return;
986
- }
987
- }
988
- if (!mustRefresh && isEligible$3(options)) {
989
- return oauthTokenStore.set(await requestToken$3(tokenFetcher, options));
990
- }
991
- if (options.authorizationRedirect &&
992
- isEligibleForClientRedirect$1(options)) {
993
- return options.authorizationRedirect(getRedirectUrl$1(options));
994
- }
995
- if (isEligible$1(options)) {
996
- return oauthTokenStore.set(await requestToken$1(tokenFetcher, options));
997
- }
998
- return;
999
- }
1000
-
1001
- function sleep(milliseconds) {
1002
- return new Promise((resolve) => setTimeout(() => resolve(true), milliseconds));
1003
- }
1004
-
1005
- const requestLogger = makeLogger('REST API Request');
1006
- const responseLogger = makeLogger('REST API Response');
1007
- const RETRYABLE_STATUS_CODES = [401, 408, 429, 502, 503, 504];
1008
- const TOKEN_REFRESH_STATUS_CODES = [401];
1009
- const queue = new Bottleneck({
1010
- maxConcurrent: QUEUE_CONCURRENCY,
1011
- minTime: QUEUE_DELAY,
1012
- reservoir: QUEUE_RESERVOIR,
1013
- });
1014
- const refillIntervalSet = new Set();
1015
- function isFormData(body) {
1016
- return typeof body !== 'undefined' && body.formData !== undefined;
1017
- }
1018
- function refillReservoir() {
1019
- if (refillIntervalSet.size === 0) {
1020
- const interval = setInterval(async () => {
1021
- const reservoir = (await queue.currentReservoir());
1022
- if (queue.empty() && (await queue.running()) === 0 && reservoir > 10) {
1023
- return ((await queue.incrementReservoir(1)) &&
1024
- clearIntervalFunction(interval) &&
1025
- refillIntervalSet.delete(interval));
1026
- }
1027
- return reservoir < QUEUE_RESERVOIR
1028
- ? queue.incrementReservoir(1)
1029
- : clearIntervalFunction(interval) && refillIntervalSet.delete(interval);
1030
- }, QUEUE_RESERVOIR_REFILL_INTERVAL);
1031
- return refillIntervalSet.add(interval);
1032
- }
1033
- return refillIntervalSet;
1034
- }
1035
- async function makeResultFromResponse(response) {
1036
- if (RETRYABLE_STATUS_CODES.includes(response.status)) {
1037
- return response.clone();
1038
- }
1039
- if (!response.ok) {
1040
- return new Error(`${response.status} ${response.statusText}\n\n${await response.text()}`);
1041
- }
1042
- if (response.headers.get('content-type') !== 'application/json' &&
1043
- response.status !== 204) {
1044
- return new Error(`Response content type was "${response.headers.get('content-type')}" but expected JSON`);
1045
- }
1046
- return {
1047
- body: response.status === 204 ? '' : await response.json(),
1048
- status: response.status,
1049
- };
1050
- }
1051
- function responseWasSuccessful(response) {
1052
- return !RETRYABLE_STATUS_CODES.includes(response.status);
1053
- }
1054
- function makeApiRequest(oauthTokenStore, oauthTokenRequester, options, httpMethod, apiMethod, payload, returnRawResultObject) {
1055
- return async (previousResult, retryCount) => {
1056
- if (retryCount > 0) {
1057
- if (retryCount > options.requestMaxRetries) {
1058
- const error = `Maximum number of retries reached while retrying ${previousResult.method} request ${previousResult.path}.`;
1059
- requestLogger.error(error);
1060
- throw new Error(error);
1061
- }
1062
- requestLogger.warn(`Warning: encountered ${previousResult.status}. Retrying ${previousResult.method} request ${previousResult.path} (retry #${retryCount}).`);
1063
- await sleep(Math.ceil(Math.random() *
1064
- options.requestBackOffInterval *
1065
- 2 ** retryCount));
1066
- }
1067
- await maybeUpdateToken(oauthTokenStore, oauthTokenRequester, options, retryCount > 0 &&
1068
- TOKEN_REFRESH_STATUS_CODES.includes(previousResult.status));
1069
- const payloadQuery = payload?.query
1070
- ? (apiMethod.includes('?') ? '&' : '?') + buildQueryString(payload.query)
1071
- : '';
1072
- const url = `${options.apiUrl}/api${apiMethod}${payloadQuery}`;
1073
- if (!oauthTokenStore.get('accessToken')) {
1074
- throw new Error(`Unable to get OAuth2 access token. Error trying to call endpoint: ${url}`);
1075
- }
1076
- try {
1077
- return (refillReservoir() &&
1078
- (await queue.schedule(async () => {
1079
- const method = httpMethod.toUpperCase();
1080
- const body = payload?.body;
1081
- const hasForm = isFormData(body);
1082
- const form = isFormData(body) ? body.formData : {};
1083
- const formData = Object.entries(form).reduce((previous, [name, value]) => {
1084
- if (Array.isArray(value)) {
1085
- const [content, filename] = value;
1086
- const blobContent = content instanceof Blob ? content : new Blob([content]);
1087
- previous.append(name, blobContent, filename);
1088
- }
1089
- else {
1090
- previous.append(name, value);
1091
- }
1092
- return previous;
1093
- }, new FormData());
1094
- const headers = {
1095
- accept: 'application/json',
1096
- authorization: `Bearer ${oauthTokenStore.get('accessToken')}`,
1097
- 'X-Allthings-Caller': `${options.serviceName
1098
- ? options.serviceName
1099
- :
1100
- process.env.SEVICE_NAME
1101
- ? process.env.SEVICE_NAME
1102
- : 'unknown service name'} --- clientID ${options.clientId?.split('_')[0] ??
1103
- options.clientId ??
1104
- 'no client id present'}`,
1105
- ...(hasForm ? {} : { 'content-type': 'application/json' }),
1106
- ...(typeof window === 'undefined' &&
1107
- typeof document === 'undefined' && { 'user-agent': USER_AGENT }),
1108
- ...payload?.headers,
1109
- };
1110
- if (process.env.LOG_REQUEST) {
1111
- console.log({ sdkLogs: { method, url } });
1112
- }
1113
- requestLogger.log(method, url, {
1114
- body,
1115
- headers,
1116
- });
1117
- const requestBody = {
1118
- body: hasForm ? formData : JSON.stringify(body),
1119
- };
1120
- const response = await fetch(url, {
1121
- cache: 'no-cache',
1122
- credentials: 'omit',
1123
- headers,
1124
- method,
1125
- mode: 'cors',
1126
- ...(hasForm || body ? requestBody : {}),
1127
- });
1128
- const result = await makeResultFromResponse(response);
1129
- responseLogger.log(method, url, result instanceof Error
1130
- ? { error: result }
1131
- : {
1132
- body: result.body,
1133
- status: response.status,
1134
- });
1135
- return result instanceof Error && returnRawResultObject
1136
- ? {
1137
- body: result.message,
1138
- status: response.status,
1139
- }
1140
- : result;
1141
- })));
1142
- }
1143
- catch (error) {
1144
- return error;
1145
- }
1146
- };
1147
- }
1148
- async function request(oauthTokenStore, oauthTokenRequester, options, httpMethod, apiMethod, payload, returnRawResultObject) {
1149
- const result = await until(responseWasSuccessful, makeApiRequest(oauthTokenStore, oauthTokenRequester, options, httpMethod, apiMethod, payload, returnRawResultObject));
1150
- if (result instanceof Error) {
1151
- requestLogger.log('Request Error', result, payload);
1152
- throw result;
1153
- }
1154
- return returnRawResultObject ? result : result.body;
1155
- }
1156
-
1157
- const API_METHODS = [
1158
- agentCreate,
1159
- agentCreatePermissions,
1160
- appCreate,
1161
- appGetById,
1162
- bucketCreate,
1163
- bucketAddFile,
1164
- bucketRemoveFile,
1165
- bucketRemoveFilesInPath,
1166
- bucketGet,
1167
- conversationGetById,
1168
- conversationCreateMessage,
1169
- fileCreate,
1170
- fileDelete,
1171
- notificationSettingsResetByUser,
1172
- notificationSettingsUpdateByUser,
1173
- groupCreate,
1174
- groupGetById,
1175
- groupUpdateById,
1176
- getGroups,
1177
- lookupIds,
1178
- notificationsGetByUser,
1179
- notificationUpdateRead,
1180
- notificationsUpdateReadByUser,
1181
- propertyCreate,
1182
- propertyGetById,
1183
- propertyUpdateById,
1184
- getProperties,
1185
- serviceProviderCreate,
1186
- serviceProviderGetById,
1187
- serviceProviderUpdateById,
1188
- registrationCodeCreate,
1189
- registrationCodeUpdateById,
1190
- registrationCodeDelete,
1191
- registrationCodeGetById,
1192
- ticketCreateOnUser,
1193
- ticketCreateOnServiceProvider,
1194
- ticketGetById,
1195
- unitCreate,
1196
- unitGetById,
1197
- unitUpdateById,
1198
- getUnits,
1199
- userCreate,
1200
- userGetById,
1201
- userUpdateById,
1202
- userChangePassword,
1203
- userCreatePermission,
1204
- userCreatePermissionBatch,
1205
- userGetPermissions,
1206
- userDeletePermission,
1207
- userCheckInToUtilisationPeriod,
1208
- userGetUtilisationPeriods,
1209
- userGetByEmail,
1210
- getCurrentUser,
1211
- getUsers,
1212
- userRelationCreate,
1213
- userRelationDelete,
1214
- userRelationsGetByUser,
1215
- utilisationPeriodCreate,
1216
- utilisationPeriodDelete,
1217
- utilisationPeriodGetById,
1218
- utilisationPeriodUpdateById,
1219
- utilisationPeriodCheckInUser,
1220
- utilisationPeriodCheckOutUser,
1221
- utilisationPeriodAddRegistrationCode,
1222
- bookingUpdateById,
1223
- bookingGetById,
1224
- ];
1225
- function restClient(userOptions = DEFAULT_API_WRAPPER_OPTIONS) {
1226
- const options = {
1227
- ...DEFAULT_API_WRAPPER_OPTIONS,
1228
- ...userOptions,
1229
- };
1230
- if (options.apiUrl === undefined) {
1231
- throw new Error('API URL is undefined.');
1232
- }
1233
- if (options.oauthUrl === undefined) {
1234
- throw new Error('OAuth2 URL is undefined.');
1235
- }
1236
- if (!options.clientId &&
1237
- !(options.accessToken || options.tokenStore) &&
1238
- typeof window === 'undefined') {
1239
- throw new Error('Missing required "clientId" or "accessToken" parameter .');
1240
- }
1241
- const tokenRequester = makeFetchTokenRequester(`${options.oauthUrl}/oauth/token`);
1242
- const tokenStore = options.tokenStore ||
1243
- createTokenStore({
1244
- accessToken: options.accessToken,
1245
- refreshToken: options.refreshToken,
1246
- });
1247
- const request$1 = partial(request, tokenStore, tokenRequester, options);
1248
- const del$1 = partial(del, request$1);
1249
- const get$1 = partial(get, request$1);
1250
- const post$1 = partial(post, request$1);
1251
- const patch$1 = partial(patch, request$1);
1252
- const put$1 = partial(put, request$1);
1253
- const oauth = {
1254
- authorizationCode: {
1255
- getUri: (state = options.state || pseudoRandomString()) => partial(getRedirectUrl$1, {
1256
- ...options,
1257
- state,
1258
- })(),
1259
- requestToken: (authorizationCode) => requestAndSaveToStore(partial(requestToken$3, tokenRequester, {
1260
- ...options,
1261
- authorizationCode: authorizationCode || options.authorizationCode,
1262
- }), tokenStore),
1263
- },
1264
- generateState: pseudoRandomString,
1265
- refreshToken: (refreshToken) => requestAndSaveToStore(partial(requestToken$2, tokenRequester, {
1266
- ...options,
1267
- refreshToken: refreshToken || tokenStore.get('refreshToken'),
1268
- }), tokenStore),
1269
- };
1270
- const client = API_METHODS.reduce((methods, method) => ({
1271
- ...methods,
1272
- [method.name]: (...arguments_) => method(client, ...arguments_),
1273
- }), {
1274
- delete: del$1,
1275
- get: get$1,
1276
- oauth,
1277
- options,
1278
- patch: patch$1,
1279
- post: post$1,
1280
- put: put$1,
1281
- });
1282
- return client;
1283
- }
1284
-
1285
- var EnumResource;
1286
- (function (EnumResource) {
1287
- EnumResource["group"] = "group";
1288
- EnumResource["property"] = "property";
1289
- EnumResource["serviceProvider"] = "propertyManager";
1290
- EnumResource["registrationCode"] = "registrationCode";
1291
- EnumResource["unit"] = "unit";
1292
- EnumResource["user"] = "user";
1293
- EnumResource["utilisationPeriod"] = "utilisationPeriod";
1294
- })(EnumResource || (EnumResource = {}));
1295
- var EnumCountryCode;
1296
- (function (EnumCountryCode) {
1297
- EnumCountryCode["CH"] = "CH";
1298
- EnumCountryCode["DE"] = "DE";
1299
- EnumCountryCode["FR"] = "FR";
1300
- EnumCountryCode["IT"] = "IT";
1301
- EnumCountryCode["NL"] = "NL";
1302
- EnumCountryCode["PT"] = "PT";
1303
- EnumCountryCode["US"] = "US";
1304
- })(EnumCountryCode || (EnumCountryCode = {}));
1305
- var EnumLocale;
1306
- (function (EnumLocale) {
1307
- EnumLocale["ch_de"] = "ch_DE";
1308
- EnumLocale["ch_fr"] = "ch_FR";
1309
- EnumLocale["ch_it"] = "ch_it";
1310
- EnumLocale["de_DE"] = "de_DE";
1311
- EnumLocale["it_IT"] = "it_IT";
1312
- EnumLocale["fr_FR"] = "fr_FR";
1313
- EnumLocale["pt_PT"] = "pt_PT";
1314
- EnumLocale["en_US"] = "en_US";
1315
- })(EnumLocale || (EnumLocale = {}));
1316
- var EnumTimezone;
1317
- (function (EnumTimezone) {
1318
- EnumTimezone["EuropeBerlin"] = "Europe/Berlin";
1319
- EnumTimezone["EuropeLondon"] = "Europe/London";
1320
- EnumTimezone["EuropeSofia"] = "Europe/Sofia";
1321
- EnumTimezone["EuropeZurich"] = "Europe/Zurich";
1322
- EnumTimezone["UTC"] = "UTC";
1323
- })(EnumTimezone || (EnumTimezone = {}));
1324
- var EnumServiceProviderType;
1325
- (function (EnumServiceProviderType) {
1326
- EnumServiceProviderType["propertyManager"] = "property-manager";
1327
- EnumServiceProviderType["craftspeople"] = "craftspeople";
1328
- })(EnumServiceProviderType || (EnumServiceProviderType = {}));
1329
- var EnumCommunicationMethodType;
1330
- (function (EnumCommunicationMethodType) {
1331
- EnumCommunicationMethodType["email"] = "email";
1332
- })(EnumCommunicationMethodType || (EnumCommunicationMethodType = {}));
1333
- var EnumInputChannel;
1334
- (function (EnumInputChannel) {
1335
- EnumInputChannel["APP"] = "app";
1336
- EnumInputChannel["COCKPIT"] = "cockpit";
1337
- EnumInputChannel["CRAFTSMEN"] = "craftsmen";
1338
- EnumInputChannel["EMAIL"] = "email";
1339
- EnumInputChannel["PHONE"] = "phone";
1340
- EnumInputChannel["WHATS_APP"] = "whats_app";
1341
- })(EnumInputChannel || (EnumInputChannel = {}));
1342
- var EnumLookupUserType;
1343
- (function (EnumLookupUserType) {
1344
- EnumLookupUserType["agent"] = "agent";
1345
- EnumLookupUserType["tenant"] = "tenant";
1346
- })(EnumLookupUserType || (EnumLookupUserType = {}));
1347
-
1348
- export { EnumCommunicationMethodType, EnumCommunicationPreferenceChannel, EnumCountryCode, EnumInputChannel, EnumLocale, EnumLookupUserType, EnumResource, EnumServiceProviderType, EnumTimezone, EnumUnitObjectType, EnumUnitType, EnumUserPermissionObjectType, EnumUserPermissionRole, EnumUserRelationType, EnumUtilisationPeriodType, buildQueryString, createTokenStore, parseQueryString, restClient };
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";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))}}const version$1="9.2.1-beta.1",environment="undefined"!=typeof process?[]:{},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:environment.ALLTHINGS_REST_API_URL||REST_API_URL,clientId:environment.ALLTHINGS_OAUTH_CLIENT_ID,clientSecret:environment.ALLTHINGS_OAUTH_CLIENT_SECRET,oauthUrl:environment.ALLTHINGS_OAUTH_URL||OAUTH_URL,password:environment.ALLTHINGS_OAUTH_PASSWORD,requestBackOffInterval:REQUEST_BACK_OFF_INTERVAL,requestMaxRetries:REQUEST_MAX_RETRIES,scope:"user:profile",username:environment.ALLTHINGS_OAUTH_USERNAME},USER_AGENT=`Allthings Node SDK REST Client/${version$1}`;function buildQueryString(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e).sort(([e],[t])=>e.localeCompare(t)))null!=r&&""!==r&&t.append(n,String(r));return t.toString()}function parseQueryString(e){const t=e.startsWith("#")?e.slice(1):e;return Object.fromEntries(new URLSearchParams(t))}const RESPONSE_TYPE$1="code",GRANT_TYPE$3="authorization_code",castToAuthorizationRequestParameters$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{client_id:n,redirect_uri:t,response_type:RESPONSE_TYPE$1,...r?{scope:r}:{},...i?{state:i}:{}}},isEligibleForClientRedirect$1=e=>{try{return!!castToAuthorizationRequestParameters$1(e)}catch{return!1}},getRedirectUrl$1=e=>`${e.oauthUrl}/oauth/authorize?${buildQueryString(castToAuthorizationRequestParameters$1(e))}`,castToTokenRequestParameters$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{client_id:r,code:t,grant_type:GRANT_TYPE$3,redirect_uri:n,...i?{client_secret:i}:{}}},isEligible$3=e=>{try{return!!castToTokenRequestParameters$2(e)}catch{return!1}},requestToken$3=(e,t)=>e(castToTokenRequestParameters$2(t)),SUBSCRIPTIONS=environment.DEBUG?.split(",").map(e=>e.trim())||[];function makeLogger(e){return["log","info","warn","error"].reduce((t,n)=>({...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:buildQueryString(t),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 instanceof Response))throw e;const t=`HTTP ${e.status} — ${e.statusText}`;throw logger.error(t,e),new Error(`HTTP ${e.status} — ${e.statusText}. Could not get token.`)}},GRANT_TYPE$2="refresh_token",castToTokenRequestParameters$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{client_id:t,grant_type:GRANT_TYPE$2,refresh_token:r,...n?{client_secret:n}:{},...i?{scope:i}:{}}},isEligible$2=e=>{try{return!!castToTokenRequestParameters$1(e)}catch{return!1}},requestToken$2=(e,t)=>e(castToTokenRequestParameters$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 clearIntervalFunction(e){return clearInterval(e),!0}function pseudoRandomString(e=16){let t="";for(;t.length<e;)t+=Math.random().toString(36).slice(2);return t.slice(0,Math.max(0,e))}async function del(e,t,n,r,i){return e("delete",t,{body:n,headers:i},r)}async function get(e,t,n,r,i){return e("get",t,{headers:i,query:n},r)}var 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,...n}=e;return{...n,tenantIds:t}},remapEmbeddedUser=e=>e.users?e.users.map(remapUserResult):[];async function userCreate(e,t,n,r){return e.post("/v1/users",{...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,...i}=n;return remapUserResult(await e.patch(`/v1/users/${t}`,{...i,tenantIDs:r}))}async function userCreatePermission(e,t,n){const{objectId:r,...i}=n,{objectID:s,...o}=await e.post(`/v1/users/${t}/permissions`,{...i,objectID:r});return{...o,objectId:s}}async function userCreatePermissionBatch(e,t,n){const{objectId:r,objectType:i,roles:s,startDate:o,endDate:a}=n,u={batch:s.map(e=>({endDate:a?.toISOString(),objectID:r,objectType:i,restrictions:[],role:e,startDate:o?.toISOString()}))};return!await e.post(`/v1/users/${t}/permissions`,u)}async function userGetPermissions(e,t){const{_embedded:{items:n}}=await e.get(`/v1/users/${t}/roles?limit=-1`);return n.map(({objectID:e,...t})=>({...t,objectId:e}))}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,{...i,type:EnumUserType.customer}),u=await e.post(`/v1/property-managers/${n}/users`,{userID:a.id,...o&&{externalAgentCompany:o}});return!((void 0===s||s)&&await e.post(`/v1/users/${a.id}/invitations`))&&{...a,...u}}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`,{availableLocales:{0:"de_DE"},...n,siteUrl:n.siteUrl.replace("_","")})}async function appGetById(e,t){return e.get(`/v1/apps/${t}`)}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 instanceof Error?e:new Error(String(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?.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}`)}async function groupCreate(e,t,n){const{propertyManagerId:r,...i}=n;return e.post(`/v1/properties/${t}/groups`,{...i,propertyManagerID:r})}async function groupGetById(e,t){const{propertyManagerID:n,...r}=await e.get(`/v1/groups/${t}`);return{...r,propertyManagerId:n}}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){const r=n.dataSource?`/v1/id-lookup/${t}/${n.resource}/${n.dataSource}`:`/v1/id-lookup/${t}/${n.resource}`;return e.post(r,{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 EnumNotificationCategory,EnumNotificationType,EnumNotificationSettingsValue;function remapNotificationResult({createdAt:e,objectID:t,referencedObjectID:n,...r}){return{createdAt:stringToDate(e),objectId:t,referencedObjectId:n,...r}}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)=>({...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={}));const remapRegistationCodeResult=e=>{const{tenantID:t,...n}=e;return{...n,externalId:t}};async function registrationCodeCreate(e,t,n,r={permanent:!1}){const{externalId:i,...s}=r;return remapRegistationCodeResult(await e.post("/v1/registration-codes",{code:t,utilisationPeriods:"string"==typeof n?[n]:n,...i?{externalId: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,EnumUtilisationPeriodType;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`,{...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`,{...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`)}async function utilisationPeriodCreate(e,t,n){const{tenantIDs:r,_embedded:i,...s}=await e.post(`/v1/units/${t}/utilisation-periods`,n);return{...s,invitations:i.invitations.map(remapRegistationCodeResult),tenantIds:r,users:remapEmbeddedUser(i)}}async function utilisationPeriodGetById(e,t){const{tenantIDs:n,_embedded:r,...i}=await e.get(`/v1/utilisation-periods/${t}`);return{...i,invitations:r.invitations.map(remapRegistationCodeResult),tenantIds:n,users:remapEmbeddedUser(r)}}async function utilisationPeriodUpdateById(e,t,n){const{tenantIDs:r,_embedded:i,...s}=await e.patch(`/v1/utilisation-periods/${t}`,n);return{...s,invitations:i.invitations.map(remapRegistationCodeResult),tenantIds:r,users:remapEmbeddedUser(i)}}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,i){return e("patch",t,{body:n,headers:i},r)}async function post(e,t,n,r,i){return e("post",t,{body:n,headers:i},r)}async function put(e,t,n,r,i){return e("put",t,{body:n,headers:i},r)}function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}!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",exports.EnumUtilisationPeriodType=void 0,EnumUtilisationPeriodType=exports.EnumUtilisationPeriodType||(exports.EnumUtilisationPeriodType={}),EnumUtilisationPeriodType.tenant="tenant",EnumUtilisationPeriodType.ownership="ownership",EnumUtilisationPeriodType.vacant="vacant";var parser={},hasRequiredParser,DLList_1,hasRequiredDLList,Events_1,hasRequiredEvents,Queues_1,hasRequiredQueues,BottleneckError_1,hasRequiredBottleneckError,Job_1,hasRequiredJob,LocalDatastore_1,hasRequiredLocalDatastore;function requireParser(){return hasRequiredParser||(hasRequiredParser=1,parser.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},parser.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}function requireDLList(){return hasRequiredDLList?DLList_1:(hasRequiredDLList=1,DLList_1=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}})}function requireEvents(){if(hasRequiredEvents)return Events_1;function e(e,t,n,r,i,s,o){try{var a=e[s](o),u=a.value}catch(e){return void n(e)}a.done?t(u):Promise.resolve(u).then(r,i)}function t(t){return function(){var n=this,r=arguments;return new Promise(function(i,s){var o=t.apply(n,r);function a(t){e(o,i,s,a,u,"next",t)}function u(t){e(o,i,s,a,u,"throw",t)}a(void 0)})}}var n;return hasRequiredEvents=1,n=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,...n){var r=this;return t(function*(){var i,s;try{if("debug"!==e&&r.trigger("debug",`Event triggered: ${e}`,n),null==r._events[e])return;return r._events[e]=r._events[e].filter(function(e){return"none"!==e.status}),s=r._events[e].map(function(){var e=t(function*(e){var t,i;if("none"!==e.status){"once"===e.status&&(e.status="none");try{return"function"==typeof(null!=(i="function"==typeof e.cb?e.cb(...n):void 0)?i.then:void 0)?yield i:i}catch(e){return t=e,r.trigger("error",t),null}}});return function(t){return e.apply(this,arguments)}}()),(yield Promise.all(s)).find(function(e){return null!=e})}catch(e){return i=e,r.trigger("error",i),null}})()}},Events_1=n}function requireQueues(){return hasRequiredQueues?Queues_1:(hasRequiredQueues=1,e=requireDLList(),t=requireEvents(),Queues_1=class{constructor(n){this.Events=new t(this),this._length=0,this._lists=function(){var t,r,i;for(i=[],t=1,r=n;1<=r?t<=r:t>=r;1<=r?++t:--t)i.push(new e(()=>this.incr(),()=>this.decr()));return i}.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 e,t}function requireBottleneckError(){return hasRequiredBottleneckError?BottleneckError_1:(hasRequiredBottleneckError=1,e=class extends Error{},BottleneckError_1=e);var e}function requireJob(){if(hasRequiredJob)return Job_1;function e(e,t,n,r,i,s,o){try{var a=e[s](o),u=a.value}catch(e){return void n(e)}a.done?t(u):Promise.resolve(u).then(r,i)}function t(t){return function(){var n=this,r=arguments;return new Promise(function(i,s){var o=t.apply(n,r);function a(t){e(o,i,s,a,u,"next",t)}function u(t){e(o,i,s,a,u,"throw",t)}a(void 0)})}}var n,r;return hasRequiredJob=1,r=requireParser(),n=requireBottleneckError(),Job_1=class{constructor(e,t,n,i,s,o,a,u){this.task=e,this.args=t,this.rejectOnDrop=s,this.Events=o,this._states=a,this.Promise=u,this.options=r.load(n,i),this.options.priority=this._sanitizePriority(this.options.priority),this.options.id===i.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?5:e)<0?0:t>9?9: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 n(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 n(`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,n,r,i){var s=this;return t(function*(){var t,o,a;0===s.retryCount?(s._assertStatus("RUNNING"),s._states.next(s.options.id)):s._assertStatus("EXECUTING"),o={args:s.args,options:s.options,retryCount:s.retryCount},s.Events.trigger("executing",o);try{if(a=yield null!=e?e.schedule(s.options,s.task,...s.args):s.task(...s.args),n())return s.doDone(o),yield i(s.options,o),s._assertStatus("DONE"),s._resolve(a)}catch(e){return t=e,s._onFailure(t,o,n,r,i)}})()}doExpire(e,t,r){var i,s;return this._states.jobStatus("RUNNING"===this.options.id)&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),s={args:this.args,options:this.options,retryCount:this.retryCount},i=new n(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(i,s,e,t,r)}_onFailure(e,n,r,i,s){var o=this;return t(function*(){var t,a;if(r())return null!=(t=yield o.Events.trigger("failed",e,n))?(a=~~t,o.Events.trigger("retry",`Retrying ${o.options.id} after ${a} ms`,n),o.retryCount++,i(a)):(o.doDone(n),yield s(o.options,n),o._assertStatus("DONE"),o._reject(e))})()}doDone(e){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",e)}}}function requireLocalDatastore(){if(hasRequiredLocalDatastore)return LocalDatastore_1;function e(e,t,n,r,i,s,o){try{var a=e[s](o),u=a.value}catch(e){return void n(e)}a.done?t(u):Promise.resolve(u).then(r,i)}function t(t){return function(){var n=this,r=arguments;return new Promise(function(i,s){var o=t.apply(n,r);function a(t){e(o,i,s,a,u,"next",t)}function u(t){e(o,i,s,a,u,"throw",t)}a(void 0)})}}var n,r;return hasRequiredLocalDatastore=1,r=requireParser(),n=requireBottleneckError(),LocalDatastore_1=class{constructor(e,t,n){this.instance=e,this.storeOptions=t,this.clientId=this.instance._randomIndex(),r.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 n=this;return t(function*(){return yield n.yieldLoop(),n.instance.Events.trigger("message",e.toString())})()}__disconnect__(e){var n=this;return t(function*(){return yield n.yieldLoop(),clearInterval(n.heartbeat),n.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 n=this;return t(function*(){return yield n.yieldLoop(),r.overwrite(e,e,n.storeOptions),n._startHeartbeat(),n.instance._drainAll(n.computeCapacity()),!0})()}__running__(){var e=this;return t(function*(){return yield e.yieldLoop(),e._running})()}__queued__(){var e=this;return t(function*(){return yield e.yieldLoop(),e.instance.queued()})()}__done__(){var e=this;return t(function*(){return yield e.yieldLoop(),e._done})()}__groupCheck__(e){var n=this;return t(function*(){return yield n.yieldLoop(),n._nextRequest+n.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 n=this;return t(function*(){var t;return yield n.yieldLoop(),t=n.storeOptions.reservoir+=e,n.instance._drainAll(n.computeCapacity()),t})()}__currentReservoir__(){var e=this;return t(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 n=this;return t(function*(){var t;return yield n.yieldLoop(),t=Date.now(),n.check(e,t)})()}__register__(e,n,r){var i=this;return t(function*(){var e,t;return yield i.yieldLoop(),e=Date.now(),i.conditionsCheck(n)?(i._running+=n,null!=i.storeOptions.reservoir&&(i.storeOptions.reservoir-=n),t=Math.max(i._nextRequest-e,0),i._nextRequest=e+t+i.storeOptions.minTime,{success:!0,wait:t,reservoir:i.storeOptions.reservoir}):{success:!1}})()}strategyIsBlock(){return 3===this.storeOptions.strategy}__submit__(e,r){var i=this;return t(function*(){var t,s,o;if(yield i.yieldLoop(),null!=i.storeOptions.maxConcurrent&&r>i.storeOptions.maxConcurrent)throw new n(`Impossible to add a job having a weight of ${r} to a limiter having a maxConcurrent setting of ${i.storeOptions.maxConcurrent}`);return s=Date.now(),o=null!=i.storeOptions.highWater&&e===i.storeOptions.highWater&&!i.check(r,s),(t=i.strategyIsBlock()&&(o||i.isBlocked(s)))&&(i._unblockTime=s+i.computePenalty(),i._nextRequest=i._unblockTime+i.storeOptions.minTime,i.instance._dropAllQueued()),{reachedHWM:o,blocked:t,strategy:i.storeOptions.strategy}})()}__free__(e,n){var r=this;return t(function*(){return yield r.yieldLoop(),r._running-=n,r._done+=n,r.instance._drainAll(r.computeCapacity()),{running:r._running}})()}}}var Scripts={},require$$0={"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"},hasRequiredScripts,RedisConnection_1,hasRequiredRedisConnection,IORedisConnection_1,hasRequiredIORedisConnection,RedisDatastore_1,hasRequiredRedisDatastore,States_1,hasRequiredStates,Sync_1,hasRequiredSync;function requireScripts(){return hasRequiredScripts||(hasRequiredScripts=1,function(e){var t,n,r;t={refs:(n=require$$0)["refs.lua"],validate_keys:n["validate_keys.lua"],validate_client:n["validate_client.lua"],refresh_expiration:n["refresh_expiration.lua"],process_tick:n["process_tick.lua"],conditions_check:n["conditions_check.lua"],get_time:n["get_time.lua"]},e.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`]},r={init:{keys:e.allKeys,headers:["process_tick"],refresh_expiration:!0,code:n["init.lua"]},group_check:{keys:e.allKeys,headers:[],refresh_expiration:!1,code:n["group_check.lua"]},register_client:{keys:e.allKeys,headers:["validate_keys"],refresh_expiration:!1,code:n["register_client.lua"]},blacklist_client:{keys:e.allKeys,headers:["validate_keys","validate_client"],refresh_expiration:!1,code:n["blacklist_client.lua"]},heartbeat:{keys:e.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:n["heartbeat.lua"]},update_settings:{keys:e.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:n["update_settings.lua"]},running:{keys:e.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:n["running.lua"]},queued:{keys:e.allKeys,headers:["validate_keys","validate_client"],refresh_expiration:!1,code:n["queued.lua"]},done:{keys:e.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:n["done.lua"]},check:{keys:e.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!1,code:n["check.lua"]},submit:{keys:e.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!0,code:n["submit.lua"]},register:{keys:e.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!0,code:n["register.lua"]},free:{keys:e.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:n["free.lua"]},current_reservoir:{keys:e.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:n["current_reservoir.lua"]},increment_reservoir:{keys:e.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:n["increment_reservoir.lua"]}},e.names=Object.keys(r),e.keys=function(e,t){return r[e].keys(t)},e.payload=function(e){var n;return n=r[e],Array.prototype.concat(t.refs,n.headers.map(function(e){return t[e]}),n.refresh_expiration?t.refresh_expiration:"",n.code).join("\n")}}(Scripts)),Scripts}function requireRedisConnection(){if(hasRequiredRedisConnection)return RedisConnection_1;function asyncGeneratorStep(e,t,n,r,i,s,o){try{var a=e[s](o),u=a.value}catch(e){return void n(e)}a.done?t(u):Promise.resolve(u).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 Events,RedisConnection,Scripts,parser;return hasRequiredRedisConnection=1,parser=requireParser(),Events=requireEvents(),Scripts=requireScripts(),RedisConnection=function(){class RedisConnection{constructor(options={}){parser.load(options,this.defaults,this),null==this.Redis&&(this.Redis=eval("require")("redis")),null==this.Events&&(this.Events=new Events(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.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.names.map(e=>this._loadScript(e)))}__runCommand__(e){var t=this;return _asyncToGenerator(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(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.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),RedisConnection_1=RedisConnection,RedisConnection_1}function requireIORedisConnection(){if(hasRequiredIORedisConnection)return IORedisConnection_1;function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}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 _arrayWithHoles(e){if(Array.isArray(e))return e}function asyncGeneratorStep(e,t,n,r,i,s,o){try{var a=e[s](o),u=a.value}catch(e){return void n(e)}a.done?t(u):Promise.resolve(u).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 Events,IORedisConnection,Scripts,parser;return hasRequiredIORedisConnection=1,parser=requireParser(),Events=requireEvents(),Scripts=requireScripts(),IORedisConnection=function(){class IORedisConnection{constructor(options={}){parser.load(options,this.defaults,this),null==this.Redis&&(this.Redis=eval("require")("ioredis")),null==this.Events&&(this.Events=new Events(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.names.forEach(e=>this.client.defineCommand(e,{lua:Scripts.payload(e)}))}__runCommand__(e){var t=this;return _asyncToGenerator(function*(){yield t.ready;var n=_slicedToArray(yield t.client.pipeline([e]).exec(),1),r=_slicedToArray(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(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.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),IORedisConnection_1=IORedisConnection,IORedisConnection_1}function requireRedisDatastore(){if(hasRequiredRedisDatastore)return RedisDatastore_1;function e(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(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}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function t(e,t,n,r,i,s,o){try{var a=e[s](o),u=a.value}catch(e){return void n(e)}a.done?t(u):Promise.resolve(u).then(r,i)}function n(e){return function(){var n=this,r=arguments;return new Promise(function(i,s){var o=e.apply(n,r);function a(e){t(o,i,s,a,u,"next",e)}function u(e){t(o,i,s,a,u,"throw",e)}a(void 0)})}}var r,i,s,o;return hasRequiredRedisDatastore=1,o=requireParser(),r=requireBottleneckError(),s=requireRedisConnection(),i=requireIORedisConnection(),RedisDatastore_1=class{constructor(e,t,n){this.instance=e,this.storeOptions=t,this.originalId=this.instance.id,this.clientId=this.instance._randomIndex(),o.load(n,n,this),this.clients={},this.capacityPriorityCounters={},this.sharedConnection=null!=this.connection,null==this.connection&&(this.connection="redis"===this.instance.datastore?new s({Redis:this.Redis,clientOptions:this.clientOptions,Promise:this.Promise,Events:this.instance.Events}):"ioredis"===this.instance.datastore?new i({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 n(function*(){return(yield t.ready).client.publish(t.instance.channel(),`message:${e.toString()}`)})()}onMessage(t,r){var i=this;return n(function*(){var t,s,o,a,u,c,l,d,h,p;try{l=r.indexOf(":");var m=[r.slice(0,l),r.slice(l+1)];if(o=m[1],"capacity"===(p=m[0]))return yield i.instance._drainAll(o.length>0?~~o:void 0);if("capacity-priority"===p){var _=e(o.split(":"),3);return h=_[0],d=_[1],s=_[2],t=h.length>0?~~h:void 0,d===i.clientId?(a=yield i.instance._drainAll(t),c=null!=t?t-(a||0):"",yield i.clients.client.publish(i.instance.channel(),`capacity-priority:${c}::${s}`)):""===d?(clearTimeout(i.capacityPriorityCounters[s]),delete i.capacityPriorityCounters[s],i.instance._drainAll(t)):i.capacityPriorityCounters[s]=setTimeout(n(function*(){var e;try{return delete i.capacityPriorityCounters[s],yield i.runScript("blacklist_client",[d]),yield i.instance._drainAll(t)}catch(t){return e=t,i.instance.Events.trigger("error",e)}}),1e3)}if("message"===p)return i.instance.Events.trigger("message",o);if("blocked"===p)return yield i.instance._dropAllQueued()}catch(e){return u=e,i.instance.Events.trigger("error",u)}})()}__disconnect__(e){return clearInterval(this.heartbeat),this.sharedConnection?this.connection.__removeLimiter__(this.instance):this.connection.disconnect(e)}runScript(e,t){var r=this;return n(function*(){return"init"!==e&&"register_client"!==e&&(yield r.ready),new r.Promise((n,i)=>{var s,o;return s=[Date.now(),r.clientId].concat(t),r.instance.Events.trigger("debug",`Calling Redis script: ${e}.lua`,s),o=r.connection.__scriptArgs__(e,r.originalId,s,function(e,t){return null!=e?i(e):n(t)}),r.connection.__scriptFn__(e)(...o)}).catch(n=>"SETTINGS_KEY_NOT_FOUND"===n.message?"heartbeat"===e?r.Promise.resolve():r.runScript("init",r.prepareInitSettings(!1)).then(()=>r.runScript(e,t)):"UNKNOWN_CLIENT"===n.message?r.runScript("register_client",[r.instance.queued()]).then(()=>r.runScript(e,t)):r.Promise.reject(n))})()}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 n(function*(){return yield t.runScript("update_settings",t.prepareObject(e)),o.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 n(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 n(function*(){return t.convertBool(yield t.runScript("check",t.prepareArray([e])))})()}__register__(t,r,i){var s=this;return n(function*(){var n,o,a,u=e(yield s.runScript("register",s.prepareArray([t,r,i])),3);return o=u[0],a=u[1],n=u[2],{success:s.convertBool(o),wait:a,reservoir:n}})()}__submit__(t,i){var s=this;return n(function*(){var n,o,a,u,c;try{var l=e(yield s.runScript("submit",s.prepareArray([t,i])),3);return u=l[0],n=l[1],c=l[2],{reachedHWM:s.convertBool(u),blocked:s.convertBool(n),strategy:c}}catch(t){if(0===(o=t).message.indexOf("OVERWEIGHT")){var d=e(o.message.split(":"),3);throw d[0],i=d[1],a=d[2],new r(`Impossible to add a job having a weight of ${i} to a limiter having a maxConcurrent setting of ${a}`)}throw o}})()}__free__(e,t){var r=this;return n(function*(){return{running:yield r.runScript("free",r.prepareArray([e]))}})()}}}function requireStates(){return hasRequiredStates?States_1:(hasRequiredStates=1,e=requireBottleneckError(),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 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(t){var n,r,i,s;if(null!=t){if((r=this.status.indexOf(t))<0)throw new e(`status must be one of ${this.status.join(", ")}`);for(n in s=[],i=this._jobs)i[n]===r&&s.push(n);return s}return Object.keys(this._jobs)}statusCounts(){return this.counts.reduce((e,t,n)=>(e[this.status[n]]=t,e),{})}});var e}function requireSync(){if(hasRequiredSync)return Sync_1;function e(e,t,n,r,i,s,o){try{var a=e[s](o),u=a.value}catch(e){return void n(e)}a.done?t(u):Promise.resolve(u).then(r,i)}function t(t){return function(){var n=this,r=arguments;return new Promise(function(i,s){var o=t.apply(n,r);function a(t){e(o,i,s,a,u,"next",t)}function u(t){e(o,i,s,a,u,"throw",t)}a(void 0)})}}var n;return hasRequiredSync=1,n=requireDLList(),Sync_1=class{constructor(e,t){this.schedule=this.schedule.bind(this),this.name=e,this.Promise=t,this._running=0,this._queue=new n}isEmpty(){return 0===this._queue.length}_tryToRun(){var e=this;return t(function*(){var n,r,i,s,o,a,u;if(e._running<1&&e._queue.length>0){e._running++;var c=e._queue.shift();return u=c.task,n=c.args,o=c.resolve,s=c.reject,r=yield t(function*(){try{return a=yield u(...n),function(){return o(a)}}catch(e){return i=e,function(){return s(i)}}})(),e._running--,e._tryToRun(),r()}})()}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}}}const version="2.19.5";var require$$8={version:version},Group_1,hasRequiredGroup,Batcher_1,hasRequiredBatcher,Bottleneck_1,hasRequiredBottleneck,lib,hasRequiredLib;function requireGroup(){if(hasRequiredGroup)return Group_1;function e(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(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}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function t(e,t,n,r,i,s,o){try{var a=e[s](o),u=a.value}catch(e){return void n(e)}a.done?t(u):Promise.resolve(u).then(r,i)}function n(e){return function(){var n=this,r=arguments;return new Promise(function(i,s){var o=e.apply(n,r);function a(e){t(o,i,s,a,u,"next",e)}function u(e){t(o,i,s,a,u,"throw",e)}a(void 0)})}}var r,i,s,o,a,u;return hasRequiredGroup=1,u=requireParser(),r=requireEvents(),o=requireRedisConnection(),s=requireIORedisConnection(),a=requireScripts(),i=function(){class t{constructor(e={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=e,u.load(this.limiterOptions,this.defaults,this),this.Events=new r(this),this.instances={},this.Bottleneck=requireBottleneck(),this._startAutoCleanup(),this.sharedConnection=null!=this.connection,null==this.connection&&("redis"===this.limiterOptions.datastore?this.connection=new o(Object.assign({},this.limiterOptions,{Events:this.Events})):"ioredis"===this.limiterOptions.datastore&&(this.connection=new s(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 n(function*(){var n,r;return r=t.instances[e],t.connection&&(n=yield t.connection.__runCommand__(["del",...a.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 t=this;return n(function*(){var n,r,i,s,o,a,u;if(null==t.connection)return t.Promise.resolve(t.keys());for(o=[],n=null,u=`b_${t.id}-`.length,9;0!==n;){var c=e(yield t.connection.__runCommand__(["scan",null!=n?n:0,"match",`b_${t.id}-*_settings`,"count",1e4]),2);for(n=~~c[0],i=0,a=(r=c[1]).length;i<a;i++)s=r[i],o.push(s.slice(u,-9))}return o})()}_startAutoCleanup(){var e,t=this;return clearInterval(this.interval),"function"==typeof(e=this.interval=setInterval(n(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(u.overwrite(e,this.defaults,this),u.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 t.prototype.defaults={timeout:3e5,connection:null,Promise:Promise,id:"group-key"},t}.call(void 0),Group_1=i}function requireBatcher(){return hasRequiredBatcher?Batcher_1:(hasRequiredBatcher=1,n=requireParser(),t=requireEvents(),e=function(){class e{constructor(e={}){this.options=e,n.load(this.options,this.defaults,this),this.Events=new t(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),Batcher_1=e);var e,t,n}function requireBottleneck(){if(hasRequiredBottleneck)return Bottleneck_1;function e(e,t){return r(e)||function(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}(e,t)||n()}function t(e){return r(e)||function(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||n()}function n(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function r(e){if(Array.isArray(e))return e}function i(e,t,n,r,i,s,o){try{var a=e[s](o),u=a.value}catch(e){return void n(e)}a.done?t(u):Promise.resolve(u).then(r,i)}function s(e){return function(){var t=this,n=arguments;return new Promise(function(r,s){var o=e.apply(t,n);function a(e){i(o,r,s,a,u,"next",e)}function u(e){i(o,r,s,a,u,"throw",e)}a(void 0)})}}hasRequiredBottleneck=1;var o,a,u,c,l,d,h,p,m,_=[].splice;return m=requireParser(),l=requireQueues(),u=requireJob(),c=requireLocalDatastore(),d=requireRedisDatastore(),a=requireEvents(),h=requireStates(),p=requireSync(),o=function(){class n{constructor(e={},...t){var r,i;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(e,t),m.load(e,this.instanceDefaults,this),this._queues=new l(10),this._scheduled={},this._states=new h(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new a(this),this._submitLock=new p("submit",this.Promise),this._registerLock=new p("register",this.Promise),i=m.load(e,this.storeDefaults,{}),this._store=function(){if("redis"===this.datastore||"ioredis"===this.datastore||null!=this.connection)return r=m.load(e,this.redisStoreDefaults,{}),new d(this,i,r);if("local"===this.datastore)return r=m.load(e,this.localStoreDefaults,{}),new c(this,i,r);throw new n.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(e,t){if(null==e||"object"!=typeof e||0!==t.length)throw new n.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 s(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 u;return this.Events.trigger("debug",`Drained ${i.id}`,{success:e,args:t,options:i}),e?(s.shift(),(u=this.empty())&&this.Events.trigger("empty"),0===a&&this.Events.trigger("depleted",u),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(e={}){var t,r;return e=m.load(e,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()}))},t=e.dropWaitingJobs?(this._run=function(t,n){return n.doDrop({message:e.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule(()=>this._submitLock.schedule(()=>{var t,n,i;for(t in n=this._scheduled)i=n[t],"RUNNING"===this.jobStatus(i.job.options.id)&&(clearTimeout(i.timeout),clearTimeout(i.expiration),i.job.doDrop({message:e.dropErrorMessage}));return this._dropAllQueued(e.dropErrorMessage),r(0)}))):this.schedule({priority:9,weight:0},()=>r(1)),this._receive=function(t){return t._reject(new n.prototype.BottleneckError(e.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new n.prototype.BottleneckError("stop() has already been called")),t}_addToQueue(e){var t=this;return s(function*(){var r,i,s,o,a,u,c;r=e.args,o=e.options;try{var l=yield t._store.__submit__(t.queued(),o.weight);a=l.reachedHWM,i=l.blocked,c=l.strategy}catch(n){return s=n,t.Events.trigger("debug",`Could not queue ${o.id}`,{args:r,options:o,error:s}),e.doDrop({error:s}),!1}return i?(e.doDrop(),!0):a&&(null!=(u=c===n.prototype.strategy.LEAK?t._queues.shiftLastFrom(o.priority):c===n.prototype.strategy.OVERFLOW_PRIORITY?t._queues.shiftLastFrom(o.priority+1):c===n.prototype.strategy.OVERFLOW?e:void 0)&&u.doDrop(),null==u||c===n.prototype.strategy.OVERFLOW)?(null==u&&e.doDrop(),a):(e.doQueue(a,i),t._queues.push(e),yield t._drainAll(),a)})()}_receive(e){return null!=this._states.jobStatus(e.options.id)?(e._reject(new n.prototype.BottleneckError(`A job with the same id already exists (id=${e.options.id})`)),!1):(e.doReceive(),this._submitLock.schedule(this._addToQueue,e))}submit(...n){var r,i,s,o,a,c,l,d,h;"function"==typeof n[0]?(c=t(n),i=c[0],n=c.slice(1),l=e(_.call(n,-1),1),r=l[0],o=m.load({},this.jobDefaults)):(o=(d=t(n))[0],i=d[1],n=d.slice(2),h=e(_.call(n,-1),1),r=h[0],o=m.load(o,this.jobDefaults));return a=(...e)=>new this.Promise(function(t,n){return i(...e,function(...e){return(null!=e[0]?n:t)(e)})}),(s=new u(a,n,o,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise)).promise.then(function(e){return"function"==typeof r?r(...e):void 0}).catch(function(e){return Array.isArray(e)?"function"==typeof r?r(...e):void 0:"function"==typeof r?r(e):void 0}),this._receive(s)}schedule(...e){var n,r,i;if("function"==typeof e[0]){var s=t(e);i=s[0],e=s.slice(1),r={}}else{var o=t(e);r=o[0],i=o[1],e=o.slice(2)}return n=new u(i,e,r,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(n),n.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 s(function*(){return yield t._store.__updateSettings__(m.overwrite(e,t.storeDefaults)),m.overwrite(e,t.instanceDefaults,t),t})()}currentReservoir(){return this._store.__currentReservoir__()}incrementReservoir(e=0){return this._store.__incrementReservoir__(e)}}return n.default=n,n.Events=a,n.version=n.prototype.version=require$$8.version,n.strategy=n.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},n.BottleneckError=n.prototype.BottleneckError=requireBottleneckError(),n.Group=n.prototype.Group=requireGroup(),n.RedisConnection=n.prototype.RedisConnection=requireRedisConnection(),n.IORedisConnection=n.prototype.IORedisConnection=requireIORedisConnection(),n.Batcher=n.prototype.Batcher=requireBatcher(),n.prototype.jobDefaults={priority:5,weight:1,expiration:null,id:"<no-id>"},n.prototype.storeDefaults={maxConcurrent:null,minTime:0,highWater:null,strategy:n.prototype.strategy.LEAK,penalty:null,reservoir:null,reservoirRefreshInterval:null,reservoirRefreshAmount:null,reservoirIncreaseInterval:null,reservoirIncreaseAmount:null,reservoirIncreaseMaximum:null},n.prototype.localStoreDefaults={Promise:Promise,timeout:null,heartbeatInterval:250},n.prototype.redisStoreDefaults={Promise:Promise,timeout:null,heartbeatInterval:5e3,clientTimeout:1e4,Redis:null,clientOptions:{},clusterNodes:null,clearDatastore:!1,connection:null},n.prototype.instanceDefaults={datastore:"local",connection:null,id:"<no-id>",rejectOnDrop:!0,trackDoneStatus:!1,Promise:Promise},n.prototype.stopDefaults={enqueueErrorMessage:"This limiter has been stopped and cannot accept new jobs.",dropWaitingJobs:!0,dropErrorMessage:"This limiter has been stopped."},n}.call(void 0),Bottleneck_1=o}function requireLib(){return hasRequiredLib?lib:(hasRequiredLib=1,lib=requireBottleneck())}var libExports=requireLib(),Bottleneck=getDefaultExportFromCjs(libExports);const GRANT_TYPE$1="client_credentials",castClientOptionsToRequestParameters=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{client_id:n,client_secret:r,grant_type:GRANT_TYPE$1,...t?{scope:t}:{}}},isEligible$1=e=>{try{return!!castClientOptionsToRequestParameters(e)}catch{return!1}},requestToken$1=(e,t)=>e(castClientOptionsToRequestParameters(t)),RESPONSE_TYPE="token",castToAuthorizationRequestParameters=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{client_id:t,redirect_uri:i||window.location.href,response_type:RESPONSE_TYPE,...n?{scope:n}:{},...r?{state:r}:{}}},isEligibleForClientRedirect=e=>{try{return!!castToAuthorizationRequestParameters(e)}catch{return!1}},getRedirectUrl=e=>`${e.oauthUrl}/oauth/authorize?${buildQueryString(castToAuthorizationRequestParameters(e))}`,GRANT_TYPE="password",castToTokenRequestParameters=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{client_id:i,grant_type:GRANT_TYPE,password:n,username:t,...r?{scope:r}:{},...s?{client_secret:s}:{}}},isEligible=e=>{try{return!!castToTokenRequestParameters(e)}catch{return!1}},requestToken=(e,t)=>e(castToTokenRequestParameters(t));async function maybeUpdateToken(e,t,n,r=!1){if(!r&&e.get("accessToken"))return;const i={...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=parseQueryString(window.location.hash).access_token;if(t)return window.history.replaceState({},"",window.location.href.split("#")[0]),e.set({accessToken:t});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 Bottleneck({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)&&clearIntervalFunction(e)&&refillIntervalSet.delete(e):t<QUEUE_RESERVOIR?queue.incrementReservoir(1):clearIntervalFunction(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,u)=>{if(u>0){if(u>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 #${u}).`),await sleep(Math.ceil(Math.random()*n.requestBackOffInterval*2**u))}await maybeUpdateToken(e,t,n,u>0&&TOKEN_REFRESH_STATUS_CODES.includes(a.status));const c=s?.query?(i.includes("?")?"&":"?")+buildQueryString(s.query):"",l=`${n.apiUrl}/api${i}${c}`;if(!e.get("accessToken"))throw new Error(`Unable to get OAuth2 access token. Error trying to call endpoint: ${l}`);try{return refillReservoir()&&await queue.schedule(async()=>{const t=r.toUpperCase(),i=s?.body,a=isFormData(i),u=isFormData(i)?i.formData:{},c=Object.entries(u).reduce((e,[t,n])=>{if(Array.isArray(n)){const[r,i]=n,s=r instanceof Blob?r:new Blob([r]);e.append(t,s,i)}else e.append(t,n);return e},new FormData),d={accept:"application/json",authorization:`Bearer ${e.get("accessToken")}`,"X-Allthings-Caller":`${n.serviceName?n.serviceName:environment.SEVICE_NAME?environment.SEVICE_NAME:"unknown service name"} --- clientID ${n.clientId?.split("_")[0]??n.clientId??"no client id present"}`,...a?{}:{"content-type":"application/json"},..."undefined"==typeof window&&"undefined"==typeof document&&{"user-agent":USER_AGENT},...s?.headers};environment.LOG_REQUEST&&console.log({sdkLogs:{method:t,url:l}}),requestLogger.log(t,l,{body:i,headers:d});const h={body:a?c:JSON.stringify(i)},p=await fetch(l,{cache:"no-cache",credentials:"omit",headers:d,method:t,mode:"cors",...a||i?h:{}}),m=await makeResultFromResponse(p);return responseLogger.log(t,l,m instanceof Error?{error:m}:{body:m.body,status:p.status}),m instanceof Error&&o?{body:m.message,status:p.status}:m})}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,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={...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),u=partial(patch,i),c=partial(put,i),l={authorizationCode:{getUri:(e=t.state||pseudoRandomString())=>partial(getRedirectUrl$1,{...t,state:e})(),requestToken:e=>requestAndSaveToStore(partial(requestToken$3,n,{...t,authorizationCode:e||t.authorizationCode}),r)},generateState:pseudoRandomString,refreshToken:e=>requestAndSaveToStore(partial(requestToken$2,n,{...t,refreshToken:e||r.get("refreshToken")}),r)},d=API_METHODS.reduce((e,t)=>({...e,[t.name]:(...e)=>t(d,...e)}),{delete:s,get:o,oauth:l,options:t,patch:u,post:a,put:c});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.buildQueryString=buildQueryString,exports.createTokenStore=createTokenStore,exports.parseQueryString=parseQueryString,exports.restClient=restClient});