@dereekb/calcom 13.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/index.cjs.default.js +1 -0
  3. package/index.cjs.js +2202 -0
  4. package/index.cjs.mjs +2 -0
  5. package/index.d.ts +1 -0
  6. package/index.esm.js +2141 -0
  7. package/nestjs/index.cjs.default.js +1 -0
  8. package/nestjs/index.cjs.js +1970 -0
  9. package/nestjs/index.cjs.mjs +2 -0
  10. package/nestjs/index.d.ts +1 -0
  11. package/nestjs/index.esm.js +1938 -0
  12. package/nestjs/package.json +28 -0
  13. package/nestjs/src/index.d.ts +1 -0
  14. package/nestjs/src/lib/calcom/calcom.api.d.ts +160 -0
  15. package/nestjs/src/lib/calcom/calcom.config.d.ts +10 -0
  16. package/nestjs/src/lib/calcom/calcom.module.d.ts +18 -0
  17. package/nestjs/src/lib/calcom/index.d.ts +3 -0
  18. package/nestjs/src/lib/index.d.ts +3 -0
  19. package/nestjs/src/lib/oauth/index.d.ts +4 -0
  20. package/nestjs/src/lib/oauth/oauth.api.d.ts +25 -0
  21. package/nestjs/src/lib/oauth/oauth.config.d.ts +22 -0
  22. package/nestjs/src/lib/oauth/oauth.module.d.ts +24 -0
  23. package/nestjs/src/lib/oauth/oauth.service.d.ts +66 -0
  24. package/nestjs/src/lib/webhook/index.d.ts +7 -0
  25. package/nestjs/src/lib/webhook/webhook.calcom.config.d.ts +11 -0
  26. package/nestjs/src/lib/webhook/webhook.calcom.controller.d.ts +8 -0
  27. package/nestjs/src/lib/webhook/webhook.calcom.d.ts +16 -0
  28. package/nestjs/src/lib/webhook/webhook.calcom.module.d.ts +20 -0
  29. package/nestjs/src/lib/webhook/webhook.calcom.service.d.ts +21 -0
  30. package/nestjs/src/lib/webhook/webhook.calcom.type.d.ts +33 -0
  31. package/nestjs/src/lib/webhook/webhook.calcom.verify.d.ts +16 -0
  32. package/package.json +34 -0
  33. package/src/index.d.ts +1 -0
  34. package/src/lib/calcom/calcom.api.booking.d.ts +86 -0
  35. package/src/lib/calcom/calcom.api.calendar.d.ts +82 -0
  36. package/src/lib/calcom/calcom.api.eventtype.d.ts +85 -0
  37. package/src/lib/calcom/calcom.api.schedule.d.ts +32 -0
  38. package/src/lib/calcom/calcom.api.slot.d.ts +46 -0
  39. package/src/lib/calcom/calcom.api.user.d.ts +29 -0
  40. package/src/lib/calcom/calcom.api.webhook.d.ts +97 -0
  41. package/src/lib/calcom/calcom.config.d.ts +66 -0
  42. package/src/lib/calcom/calcom.error.api.d.ts +6 -0
  43. package/src/lib/calcom/calcom.factory.d.ts +23 -0
  44. package/src/lib/calcom/index.d.ts +10 -0
  45. package/src/lib/calcom.config.d.ts +35 -0
  46. package/src/lib/calcom.error.api.d.ts +86 -0
  47. package/src/lib/calcom.limit.d.ts +35 -0
  48. package/src/lib/calcom.type.d.ts +70 -0
  49. package/src/lib/index.d.ts +7 -0
  50. package/src/lib/oauth/index.d.ts +5 -0
  51. package/src/lib/oauth/oauth.api.d.ts +54 -0
  52. package/src/lib/oauth/oauth.config.d.ts +53 -0
  53. package/src/lib/oauth/oauth.d.ts +64 -0
  54. package/src/lib/oauth/oauth.error.api.d.ts +26 -0
  55. package/src/lib/oauth/oauth.factory.d.ts +31 -0
  56. package/src/lib/shared/calcom.api-version.d.ts +17 -0
  57. package/src/lib/shared/index.d.ts +1 -0
@@ -0,0 +1,1938 @@
1
+ import { Injectable, Inject, Logger, Post, Res, Req, Controller, Module } from '@nestjs/common';
2
+ import { calcomOAuthFactory, exchangeAuthorizationCode, calcomFactory, getMe, getSchedules, createBooking, getBooking, cancelBooking, getEventTypes, createEventType, updateEventType, deleteEventType, getCalendars, getBusyTimes, createWebhook, getWebhooks, getWebhook, updateWebhook, deleteWebhook, getAvailableSlots } from '@dereekb/calcom';
3
+ import { tryWithPromiseFactoriesFunction, isPast, filterMaybeArrayValues, cachedGetter, handlerFactory, handlerConfigurerFactory, handlerMappedSetFunctionFactory } from '@dereekb/util';
4
+ import { createHash, createHmac } from 'crypto';
5
+ import { join, dirname } from 'path';
6
+ import { mkdirSync, writeFile, readFile } from 'fs';
7
+ import { ConfigService, ConfigModule } from '@nestjs/config';
8
+ import { RawBody } from '@dereekb/nestjs';
9
+
10
+ function _type_of(obj) {
11
+ "@swc/helpers - typeof";
12
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
13
+ }
14
+ function __decorate(decorators, target, key, desc) {
15
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16
+ if ((typeof Reflect === "undefined" ? "undefined" : _type_of(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
17
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
18
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
19
+ }
20
+ function __param(paramIndex, decorator) {
21
+ return function(target, key) {
22
+ decorator(target, key, paramIndex);
23
+ };
24
+ }
25
+ typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
26
+ var e = new Error(message);
27
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
28
+ };
29
+
30
+ function _class_call_check$8(instance, Constructor) {
31
+ if (!(instance instanceof Constructor)) {
32
+ throw new TypeError("Cannot call a class as a function");
33
+ }
34
+ }
35
+ function _defineProperties$6(target, props) {
36
+ for(var i = 0; i < props.length; i++){
37
+ var descriptor = props[i];
38
+ descriptor.enumerable = descriptor.enumerable || false;
39
+ descriptor.configurable = true;
40
+ if ("value" in descriptor) descriptor.writable = true;
41
+ Object.defineProperty(target, descriptor.key, descriptor);
42
+ }
43
+ }
44
+ function _create_class$6(Constructor, protoProps, staticProps) {
45
+ if (staticProps) _defineProperties$6(Constructor, staticProps);
46
+ return Constructor;
47
+ }
48
+ function _define_property$7(obj, key, value) {
49
+ if (key in obj) {
50
+ Object.defineProperty(obj, key, {
51
+ value: value,
52
+ enumerable: true,
53
+ configurable: true,
54
+ writable: true
55
+ });
56
+ } else {
57
+ obj[key] = value;
58
+ }
59
+ return obj;
60
+ }
61
+ var CALCOM_SERVICE_NAME = 'calcom';
62
+ var CALCOM_CLIENT_ID_CONFIG_KEY = 'CALCOM_CLIENT_ID';
63
+ var CALCOM_CLIENT_SECRET_CONFIG_KEY = 'CALCOM_CLIENT_SECRET';
64
+ var CALCOM_REFRESH_TOKEN_CONFIG_KEY = 'CALCOM_REFRESH_TOKEN';
65
+ var CALCOM_API_KEY_CONFIG_KEY = 'CALCOM_API_KEY';
66
+ /**
67
+ * Configuration for CalcomOAuthService
68
+ */ var CalcomOAuthServiceConfig = /*#__PURE__*/ function() {
69
+ function CalcomOAuthServiceConfig() {
70
+ _class_call_check$8(this, CalcomOAuthServiceConfig);
71
+ _define_property$7(this, "calcomOAuth", void 0);
72
+ _define_property$7(this, "factoryConfig", void 0);
73
+ }
74
+ _create_class$6(CalcomOAuthServiceConfig, null, [
75
+ {
76
+ key: "assertValidConfig",
77
+ value: function assertValidConfig(config) {
78
+ var calcomOAuth = config.calcomOAuth;
79
+ if (!calcomOAuth) {
80
+ throw new Error('CalcomOAuthServiceConfig.calcomOAuth is required');
81
+ }
82
+ var hasApiKey = !!calcomOAuth.apiKey;
83
+ var hasOAuth = !!calcomOAuth.clientId && !!calcomOAuth.clientSecret;
84
+ if (!hasApiKey && !hasOAuth) {
85
+ throw new Error('CalcomOAuthServiceConfig requires either apiKey or clientId+clientSecret');
86
+ }
87
+ }
88
+ }
89
+ ]);
90
+ return CalcomOAuthServiceConfig;
91
+ }();
92
+ function calcomOAuthServiceConfigFactory(configService) {
93
+ var clientId = configService.get(CALCOM_CLIENT_ID_CONFIG_KEY);
94
+ var clientSecret = configService.get(CALCOM_CLIENT_SECRET_CONFIG_KEY);
95
+ var refreshToken = configService.get(CALCOM_REFRESH_TOKEN_CONFIG_KEY);
96
+ var apiKey = configService.get(CALCOM_API_KEY_CONFIG_KEY);
97
+ var config = {
98
+ calcomOAuth: {
99
+ clientId: clientId || undefined,
100
+ clientSecret: clientSecret || undefined,
101
+ refreshToken: refreshToken || undefined,
102
+ apiKey: apiKey || undefined
103
+ }
104
+ };
105
+ CalcomOAuthServiceConfig.assertValidConfig(config);
106
+ return config;
107
+ }
108
+
109
+ function _array_like_to_array$3(arr, len) {
110
+ if (len == null || len > arr.length) len = arr.length;
111
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
112
+ return arr2;
113
+ }
114
+ function _array_with_holes(arr) {
115
+ if (Array.isArray(arr)) return arr;
116
+ }
117
+ function _array_without_holes$3(arr) {
118
+ if (Array.isArray(arr)) return _array_like_to_array$3(arr);
119
+ }
120
+ function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
121
+ try {
122
+ var info = gen[key](arg);
123
+ var value = info.value;
124
+ } catch (error) {
125
+ reject(error);
126
+ return;
127
+ }
128
+ if (info.done) {
129
+ resolve(value);
130
+ } else {
131
+ Promise.resolve(value).then(_next, _throw);
132
+ }
133
+ }
134
+ function _async_to_generator$2(fn) {
135
+ return function() {
136
+ var self = this, args = arguments;
137
+ return new Promise(function(resolve, reject) {
138
+ var gen = fn.apply(self, args);
139
+ function _next(value) {
140
+ asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
141
+ }
142
+ function _throw(err) {
143
+ asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
144
+ }
145
+ _next(undefined);
146
+ });
147
+ };
148
+ }
149
+ function _class_call_check$7(instance, Constructor) {
150
+ if (!(instance instanceof Constructor)) {
151
+ throw new TypeError("Cannot call a class as a function");
152
+ }
153
+ }
154
+ function _iterable_to_array$3(iter) {
155
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
156
+ }
157
+ function _iterable_to_array_limit(arr, i) {
158
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
159
+ if (_i == null) return;
160
+ var _arr = [];
161
+ var _n = true;
162
+ var _d = false;
163
+ var _s, _e;
164
+ try {
165
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
166
+ _arr.push(_s.value);
167
+ if (i && _arr.length === i) break;
168
+ }
169
+ } catch (err) {
170
+ _d = true;
171
+ _e = err;
172
+ } finally{
173
+ try {
174
+ if (!_n && _i["return"] != null) _i["return"]();
175
+ } finally{
176
+ if (_d) throw _e;
177
+ }
178
+ }
179
+ return _arr;
180
+ }
181
+ function _non_iterable_rest() {
182
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
183
+ }
184
+ function _non_iterable_spread$3() {
185
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
186
+ }
187
+ function _sliced_to_array(arr, i) {
188
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array$3(arr, i) || _non_iterable_rest();
189
+ }
190
+ function _to_consumable_array$3(arr) {
191
+ return _array_without_holes$3(arr) || _iterable_to_array$3(arr) || _unsupported_iterable_to_array$3(arr) || _non_iterable_spread$3();
192
+ }
193
+ function _unsupported_iterable_to_array$3(o, minLen) {
194
+ if (!o) return;
195
+ if (typeof o === "string") return _array_like_to_array$3(o, minLen);
196
+ var n = Object.prototype.toString.call(o).slice(8, -1);
197
+ if (n === "Object" && o.constructor) n = o.constructor.name;
198
+ if (n === "Map" || n === "Set") return Array.from(n);
199
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$3(o, minLen);
200
+ }
201
+ function _ts_generator$2(thisArg, body) {
202
+ var f, y, t, _ = {
203
+ label: 0,
204
+ sent: function() {
205
+ if (t[0] & 1) throw t[1];
206
+ return t[1];
207
+ },
208
+ trys: [],
209
+ ops: []
210
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
211
+ return d(g, "next", {
212
+ value: verb(0)
213
+ }), d(g, "throw", {
214
+ value: verb(1)
215
+ }), d(g, "return", {
216
+ value: verb(2)
217
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
218
+ value: function() {
219
+ return this;
220
+ }
221
+ }), g;
222
+ function verb(n) {
223
+ return function(v) {
224
+ return step([
225
+ n,
226
+ v
227
+ ]);
228
+ };
229
+ }
230
+ function step(op) {
231
+ if (f) throw new TypeError("Generator is already executing.");
232
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
233
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
234
+ if (y = 0, t) op = [
235
+ op[0] & 2,
236
+ t.value
237
+ ];
238
+ switch(op[0]){
239
+ case 0:
240
+ case 1:
241
+ t = op;
242
+ break;
243
+ case 4:
244
+ _.label++;
245
+ return {
246
+ value: op[1],
247
+ done: false
248
+ };
249
+ case 5:
250
+ _.label++;
251
+ y = op[1];
252
+ op = [
253
+ 0
254
+ ];
255
+ continue;
256
+ case 7:
257
+ op = _.ops.pop();
258
+ _.trys.pop();
259
+ continue;
260
+ default:
261
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
262
+ _ = 0;
263
+ continue;
264
+ }
265
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
266
+ _.label = op[1];
267
+ break;
268
+ }
269
+ if (op[0] === 6 && _.label < t[1]) {
270
+ _.label = t[1];
271
+ t = op;
272
+ break;
273
+ }
274
+ if (t && _.label < t[2]) {
275
+ _.label = t[2];
276
+ _.ops.push(op);
277
+ break;
278
+ }
279
+ if (t[2]) _.ops.pop();
280
+ _.trys.pop();
281
+ continue;
282
+ }
283
+ op = body.call(thisArg, _);
284
+ } catch (e) {
285
+ op = [
286
+ 6,
287
+ e
288
+ ];
289
+ y = 0;
290
+ } finally{
291
+ f = t = 0;
292
+ }
293
+ if (op[0] & 5) throw op[1];
294
+ return {
295
+ value: op[0] ? op[1] : void 0,
296
+ done: true
297
+ };
298
+ }
299
+ }
300
+ /**
301
+ * Service used for retrieving CalcomAccessTokenCache for Cal.com services.
302
+ *
303
+ * Implementations store and retrieve OAuth access tokens (and the rotated refresh tokens
304
+ * embedded in them). The service supports both a server-level cache and per-user caches
305
+ * keyed by the user's initial refresh token.
306
+ */ var CalcomOAuthAccessTokenCacheService = function CalcomOAuthAccessTokenCacheService() {
307
+ _class_call_check$7(this, CalcomOAuthAccessTokenCacheService);
308
+ };
309
+ CalcomOAuthAccessTokenCacheService = __decorate([
310
+ Injectable()
311
+ ], CalcomOAuthAccessTokenCacheService);
312
+ /**
313
+ * Derives a short, filesystem-safe cache key from a refresh token using md5.
314
+ */ function calcomRefreshTokenCacheKey(refreshToken) {
315
+ return createHash('md5').update(refreshToken).digest('hex').substring(0, 16);
316
+ }
317
+ function logMergeCalcomOAuthAccessTokenCacheServiceErrorFunction(failedUpdates) {
318
+ console.warn("mergeCalcomOAuthAccessTokenCacheServices(): failed updating ".concat(failedUpdates.length, " caches."));
319
+ failedUpdates.forEach(function(param, i) {
320
+ var _param = _sliced_to_array(param, 2); _param[0]; var e = _param[1];
321
+ console.warn("Cache update failure ".concat(i + 1, ": - ").concat(e));
322
+ });
323
+ }
324
+ /**
325
+ * Merges the input services in order to use some as a backup source.
326
+ *
327
+ * If one source fails retrieval, the next will be tried.
328
+ * When updating a cached token, it will update the token across all services.
329
+ *
330
+ * @param inputServicesToMerge Must include at least one service. Empty arrays will throw an error.
331
+ */ function mergeCalcomOAuthAccessTokenCacheServices(inputServicesToMerge, logError) {
332
+ var allServices = _to_consumable_array$3(inputServicesToMerge);
333
+ var logErrorFunction = typeof logError === 'function' ? logError : logError !== false ? logMergeCalcomOAuthAccessTokenCacheServiceErrorFunction : undefined;
334
+ if (allServices.length === 0) {
335
+ throw new Error('mergeCalcomOAuthAccessTokenCacheServices() input cannot be empty.');
336
+ }
337
+ var loadCalcomAccessTokenCache = function loadCalcomAccessTokenCache(accessCachesForServices) {
338
+ var loadCachedTokenFromFirstService = tryWithPromiseFactoriesFunction({
339
+ promiseFactories: accessCachesForServices.map(function(x) {
340
+ return function() {
341
+ return x.loadCachedToken().catch(function() {
342
+ return null;
343
+ }).then(function(x) {
344
+ var result = undefined;
345
+ if (x && !isPast(x.expiresAt)) {
346
+ result = x; // only return from cache if it is not expired
347
+ }
348
+ return result;
349
+ });
350
+ };
351
+ }),
352
+ successOnMaybe: false,
353
+ throwErrors: false
354
+ });
355
+ var cacheForService = {
356
+ loadCachedToken: function loadCachedToken() {
357
+ return loadCachedTokenFromFirstService();
358
+ },
359
+ updateCachedToken: function updateCachedToken(accessToken) {
360
+ return _async_to_generator$2(function() {
361
+ return _ts_generator$2(this, function(_state) {
362
+ return [
363
+ 2,
364
+ Promise.allSettled(accessCachesForServices.map(function(x) {
365
+ return x.updateCachedToken(accessToken).then(function() {
366
+ return null;
367
+ }).catch(function(e) {
368
+ return [
369
+ x,
370
+ e
371
+ ];
372
+ });
373
+ })).then(function(x) {
374
+ // only find the failures if we're logging
375
+ if (logErrorFunction != null) {
376
+ var failedUpdates = filterMaybeArrayValues(x.map(function(y) {
377
+ return y.value;
378
+ }));
379
+ if (failedUpdates.length) {
380
+ logErrorFunction(failedUpdates);
381
+ }
382
+ }
383
+ })
384
+ ];
385
+ });
386
+ })();
387
+ }
388
+ };
389
+ return cacheForService;
390
+ };
391
+ var allServiceAccessTokenCaches = allServices.map(function(x) {
392
+ return x.loadCalcomAccessTokenCache();
393
+ });
394
+ var allServicesWithCacheForRefreshToken = allServices.filter(function(x) {
395
+ return x.cacheForRefreshToken != null;
396
+ });
397
+ var cacheForRefreshToken = allServicesWithCacheForRefreshToken.length > 0 ? function(refreshToken) {
398
+ var allCaches = allServicesWithCacheForRefreshToken.map(function(x) {
399
+ return x.cacheForRefreshToken(refreshToken);
400
+ });
401
+ return loadCalcomAccessTokenCache(allCaches);
402
+ } : undefined;
403
+ var service = {
404
+ loadCalcomAccessTokenCache: function loadCalcomAccessTokenCache1() {
405
+ return loadCalcomAccessTokenCache(allServiceAccessTokenCaches);
406
+ },
407
+ cacheForRefreshToken: cacheForRefreshToken
408
+ };
409
+ return service;
410
+ }
411
+ // MARK: Memory Access Token Cache
412
+ /**
413
+ * Creates a CalcomOAuthAccessTokenCacheService that uses in-memory storage.
414
+ * Per-user caches are stored in a Map keyed by the md5 hash of the refresh token.
415
+ */ function memoryCalcomOAuthAccessTokenCacheService(existingToken, logAccessToConsole) {
416
+ var serverToken = existingToken;
417
+ var userTokens = new Map();
418
+ function makeCache(getToken, setToken) {
419
+ return {
420
+ loadCachedToken: function loadCachedToken() {
421
+ return _async_to_generator$2(function() {
422
+ var token;
423
+ return _ts_generator$2(this, function(_state) {
424
+ token = getToken();
425
+ if (logAccessToConsole) {
426
+ console.log('retrieving access token from memory: ', {
427
+ token: token
428
+ });
429
+ }
430
+ return [
431
+ 2,
432
+ token
433
+ ];
434
+ });
435
+ })();
436
+ },
437
+ updateCachedToken: function updateCachedToken(accessToken) {
438
+ return _async_to_generator$2(function() {
439
+ return _ts_generator$2(this, function(_state) {
440
+ setToken(accessToken);
441
+ if (logAccessToConsole) {
442
+ console.log('updating access token in memory: ', {
443
+ accessToken: accessToken
444
+ });
445
+ }
446
+ return [
447
+ 2
448
+ ];
449
+ });
450
+ })();
451
+ }
452
+ };
453
+ }
454
+ return {
455
+ loadCalcomAccessTokenCache: function loadCalcomAccessTokenCache() {
456
+ return makeCache(function() {
457
+ return serverToken;
458
+ }, function(t) {
459
+ serverToken = t;
460
+ });
461
+ },
462
+ cacheForRefreshToken: function cacheForRefreshToken(refreshToken) {
463
+ var key = calcomRefreshTokenCacheKey(refreshToken);
464
+ return makeCache(function() {
465
+ return userTokens.get(key);
466
+ }, function(t) {
467
+ return userTokens.set(key, t);
468
+ });
469
+ }
470
+ };
471
+ }
472
+ // MARK: File System Access Token Cache
473
+ var DEFAULT_FILE_CALCOM_ACCESS_TOKEN_CACHE_DIR = '.tmp/calcom-tokens';
474
+ var CALCOM_SERVER_TOKEN_FILE_KEY = 'server';
475
+ /**
476
+ * Creates a CalcomOAuthAccessTokenCacheService that reads and writes access tokens
477
+ * to the file system. Each user gets their own file, keyed by an md5 hash of their refresh token.
478
+ *
479
+ * File structure:
480
+ * ```
481
+ * <cacheDir>/
482
+ * server.json — server-level token
483
+ * user-<md5hash>.json — per-user tokens (hash of initial refresh token)
484
+ * ```
485
+ *
486
+ * @param cacheDir Directory to store token files. Defaults to `.tmp/calcom-tokens`.
487
+ */ function fileCalcomOAuthAccessTokenCacheService() {
488
+ var cacheDir = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : DEFAULT_FILE_CALCOM_ACCESS_TOKEN_CACHE_DIR;
489
+ var memoryTokens = new Map();
490
+ function filePathForKey(key) {
491
+ return join(cacheDir, "".concat(key, ".json"));
492
+ }
493
+ function readTokenFile(filePath) {
494
+ return new Promise(function(resolve) {
495
+ mkdirSync(dirname(filePath), {
496
+ recursive: true
497
+ });
498
+ readFile(filePath, {}, function(err, data) {
499
+ var result = undefined;
500
+ if (!err) {
501
+ try {
502
+ result = JSON.parse(data.toString());
503
+ if (result === null || result === void 0 ? void 0 : result.token) {
504
+ result.token.expiresAt = new Date(result.token.expiresAt);
505
+ }
506
+ } catch (e) {
507
+ console.error("Failed reading token file ".concat(filePath, ": "), e);
508
+ }
509
+ }
510
+ resolve(result);
511
+ });
512
+ });
513
+ }
514
+ function writeTokenFile(filePath, content) {
515
+ return new Promise(function(resolve, reject) {
516
+ mkdirSync(dirname(filePath), {
517
+ recursive: true
518
+ });
519
+ writeFile(filePath, JSON.stringify(content, null, 2), {}, function(err) {
520
+ if (!err) {
521
+ resolve();
522
+ } else {
523
+ reject(err);
524
+ }
525
+ });
526
+ });
527
+ }
528
+ function makeCacheForKey(fileKey) {
529
+ var filePath = filePathForKey(fileKey);
530
+ return {
531
+ loadCachedToken: function loadCachedToken() {
532
+ return _async_to_generator$2(function() {
533
+ var memoryEntry, fileContent;
534
+ return _ts_generator$2(this, function(_state) {
535
+ switch(_state.label){
536
+ case 0:
537
+ // Check memory first
538
+ memoryEntry = memoryTokens.get(fileKey);
539
+ if (memoryEntry !== undefined) {
540
+ return [
541
+ 2,
542
+ memoryEntry === null || memoryEntry === void 0 ? void 0 : memoryEntry.token
543
+ ];
544
+ }
545
+ return [
546
+ 4,
547
+ readTokenFile(filePath)
548
+ ];
549
+ case 1:
550
+ fileContent = _state.sent();
551
+ memoryTokens.set(fileKey, fileContent !== null && fileContent !== void 0 ? fileContent : null);
552
+ return [
553
+ 2,
554
+ fileContent === null || fileContent === void 0 ? void 0 : fileContent.token
555
+ ];
556
+ }
557
+ });
558
+ })();
559
+ },
560
+ updateCachedToken: function updateCachedToken(accessToken) {
561
+ return _async_to_generator$2(function() {
562
+ var content, e;
563
+ return _ts_generator$2(this, function(_state) {
564
+ switch(_state.label){
565
+ case 0:
566
+ content = {
567
+ token: accessToken
568
+ };
569
+ memoryTokens.set(fileKey, content);
570
+ _state.label = 1;
571
+ case 1:
572
+ _state.trys.push([
573
+ 1,
574
+ 3,
575
+ ,
576
+ 4
577
+ ]);
578
+ return [
579
+ 4,
580
+ writeTokenFile(filePath, content)
581
+ ];
582
+ case 2:
583
+ _state.sent();
584
+ return [
585
+ 3,
586
+ 4
587
+ ];
588
+ case 3:
589
+ e = _state.sent();
590
+ console.error("Failed updating token file ".concat(filePath, ": "), e);
591
+ return [
592
+ 3,
593
+ 4
594
+ ];
595
+ case 4:
596
+ return [
597
+ 2
598
+ ];
599
+ }
600
+ });
601
+ })();
602
+ }
603
+ };
604
+ }
605
+ return {
606
+ cacheDir: cacheDir,
607
+ loadCalcomAccessTokenCache: function loadCalcomAccessTokenCache() {
608
+ return makeCacheForKey(CALCOM_SERVER_TOKEN_FILE_KEY);
609
+ },
610
+ cacheForRefreshToken: function cacheForRefreshToken(refreshToken) {
611
+ return makeCacheForKey("user-".concat(calcomRefreshTokenCacheKey(refreshToken)));
612
+ }
613
+ };
614
+ }
615
+
616
+ function _class_call_check$6(instance, Constructor) {
617
+ if (!(instance instanceof Constructor)) {
618
+ throw new TypeError("Cannot call a class as a function");
619
+ }
620
+ }
621
+ function _defineProperties$5(target, props) {
622
+ for(var i = 0; i < props.length; i++){
623
+ var descriptor = props[i];
624
+ descriptor.enumerable = descriptor.enumerable || false;
625
+ descriptor.configurable = true;
626
+ if ("value" in descriptor) descriptor.writable = true;
627
+ Object.defineProperty(target, descriptor.key, descriptor);
628
+ }
629
+ }
630
+ function _create_class$5(Constructor, protoProps, staticProps) {
631
+ if (protoProps) _defineProperties$5(Constructor.prototype, protoProps);
632
+ return Constructor;
633
+ }
634
+ function _define_property$6(obj, key, value) {
635
+ if (key in obj) {
636
+ Object.defineProperty(obj, key, {
637
+ value: value,
638
+ enumerable: true,
639
+ configurable: true,
640
+ writable: true
641
+ });
642
+ } else {
643
+ obj[key] = value;
644
+ }
645
+ return obj;
646
+ }
647
+ var CalcomOAuthApi = /*#__PURE__*/ function() {
648
+ function CalcomOAuthApi(config, cacheService) {
649
+ _class_call_check$6(this, CalcomOAuthApi);
650
+ var _config_factoryConfig;
651
+ _define_property$6(this, "config", void 0);
652
+ _define_property$6(this, "cacheService", void 0);
653
+ _define_property$6(this, "calcomOAuth", void 0);
654
+ this.config = config;
655
+ this.cacheService = cacheService;
656
+ var accessTokenCache = cacheService.loadCalcomAccessTokenCache();
657
+ var _config_calcomOAuth = config.calcomOAuth, clientId = _config_calcomOAuth.clientId, clientSecret = _config_calcomOAuth.clientSecret, refreshToken = _config_calcomOAuth.refreshToken, apiKey = _config_calcomOAuth.apiKey;
658
+ this.calcomOAuth = calcomOAuthFactory((_config_factoryConfig = config.factoryConfig) !== null && _config_factoryConfig !== void 0 ? _config_factoryConfig : {})({
659
+ accessTokenCache: accessTokenCache,
660
+ clientId: clientId !== null && clientId !== void 0 ? clientId : '',
661
+ clientSecret: clientSecret !== null && clientSecret !== void 0 ? clientSecret : '',
662
+ refreshToken: refreshToken,
663
+ apiKey: apiKey
664
+ });
665
+ }
666
+ _create_class$5(CalcomOAuthApi, [
667
+ {
668
+ key: "oauthContext",
669
+ get: function get() {
670
+ return this.calcomOAuth.oauthContext;
671
+ }
672
+ },
673
+ {
674
+ key: "exchangeAuthorizationCode",
675
+ get: // MARK: Accessors
676
+ /** Configured pass-through for {@link exchangeAuthorizationCode}. */ function get() {
677
+ return exchangeAuthorizationCode(this.oauthContext);
678
+ }
679
+ },
680
+ {
681
+ /**
682
+ * Retrieves an access token for a specific user using their refresh token.
683
+ */ key: "userAccessToken",
684
+ value: function userAccessToken(input) {
685
+ var factory = this.oauthContext.makeUserAccessTokenFactory(input);
686
+ return factory();
687
+ }
688
+ },
689
+ {
690
+ /**
691
+ * Returns a per-user CalcomAccessTokenCache derived from the refresh token (md5 hashed as the file key).
692
+ * Returns undefined if the cache service does not support per-user caching.
693
+ */ key: "cacheForRefreshToken",
694
+ value: function cacheForRefreshToken(refreshToken) {
695
+ var _this_cacheService_cacheForRefreshToken, _this_cacheService;
696
+ return (_this_cacheService_cacheForRefreshToken = (_this_cacheService = this.cacheService).cacheForRefreshToken) === null || _this_cacheService_cacheForRefreshToken === void 0 ? void 0 : _this_cacheService_cacheForRefreshToken.call(_this_cacheService, refreshToken);
697
+ }
698
+ }
699
+ ]);
700
+ return CalcomOAuthApi;
701
+ }();
702
+ CalcomOAuthApi = __decorate([
703
+ Injectable(),
704
+ __param(0, Inject(CalcomOAuthServiceConfig)),
705
+ __param(1, Inject(CalcomOAuthAccessTokenCacheService))
706
+ ], CalcomOAuthApi);
707
+
708
+ function _array_like_to_array$2(arr, len) {
709
+ if (len == null || len > arr.length) len = arr.length;
710
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
711
+ return arr2;
712
+ }
713
+ function _array_without_holes$2(arr) {
714
+ if (Array.isArray(arr)) return _array_like_to_array$2(arr);
715
+ }
716
+ function _iterable_to_array$2(iter) {
717
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
718
+ }
719
+ function _non_iterable_spread$2() {
720
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
721
+ }
722
+ function _to_consumable_array$2(arr) {
723
+ return _array_without_holes$2(arr) || _iterable_to_array$2(arr) || _unsupported_iterable_to_array$2(arr) || _non_iterable_spread$2();
724
+ }
725
+ function _unsupported_iterable_to_array$2(o, minLen) {
726
+ if (!o) return;
727
+ if (typeof o === "string") return _array_like_to_array$2(o, minLen);
728
+ var n = Object.prototype.toString.call(o).slice(8, -1);
729
+ if (n === "Object" && o.constructor) n = o.constructor.name;
730
+ if (n === "Map" || n === "Set") return Array.from(n);
731
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$2(o, minLen);
732
+ }
733
+ /**
734
+ * Convenience function used to generate ModuleMetadata for an app's CalcomOAuthModule.
735
+ */ function appCalcomOAuthModuleMetadata(config) {
736
+ var _config_calcomOAuthServiceConfigFactory;
737
+ var dependencyModule = config.dependencyModule, imports = config.imports, exports$1 = config.exports, providers = config.providers;
738
+ var dependencyModuleImport = dependencyModule ? [
739
+ dependencyModule
740
+ ] : [];
741
+ return {
742
+ imports: [
743
+ ConfigModule
744
+ ].concat(_to_consumable_array$2(dependencyModuleImport), _to_consumable_array$2(imports !== null && imports !== void 0 ? imports : [])),
745
+ exports: [
746
+ CalcomOAuthApi
747
+ ].concat(_to_consumable_array$2(exports$1 !== null && exports$1 !== void 0 ? exports$1 : [])),
748
+ providers: [
749
+ {
750
+ provide: CalcomOAuthServiceConfig,
751
+ inject: [
752
+ ConfigService
753
+ ],
754
+ useFactory: (_config_calcomOAuthServiceConfigFactory = config.calcomOAuthServiceConfigFactory) !== null && _config_calcomOAuthServiceConfigFactory !== void 0 ? _config_calcomOAuthServiceConfigFactory : calcomOAuthServiceConfigFactory
755
+ },
756
+ CalcomOAuthApi
757
+ ].concat(_to_consumable_array$2(providers !== null && providers !== void 0 ? providers : []))
758
+ };
759
+ }
760
+
761
+ function _class_call_check$5(instance, Constructor) {
762
+ if (!(instance instanceof Constructor)) {
763
+ throw new TypeError("Cannot call a class as a function");
764
+ }
765
+ }
766
+ function _defineProperties$4(target, props) {
767
+ for(var i = 0; i < props.length; i++){
768
+ var descriptor = props[i];
769
+ descriptor.enumerable = descriptor.enumerable || false;
770
+ descriptor.configurable = true;
771
+ if ("value" in descriptor) descriptor.writable = true;
772
+ Object.defineProperty(target, descriptor.key, descriptor);
773
+ }
774
+ }
775
+ function _create_class$4(Constructor, protoProps, staticProps) {
776
+ if (staticProps) _defineProperties$4(Constructor, staticProps);
777
+ return Constructor;
778
+ }
779
+ function _define_property$5(obj, key, value) {
780
+ if (key in obj) {
781
+ Object.defineProperty(obj, key, {
782
+ value: value,
783
+ enumerable: true,
784
+ configurable: true,
785
+ writable: true
786
+ });
787
+ } else {
788
+ obj[key] = value;
789
+ }
790
+ return obj;
791
+ }
792
+ /**
793
+ * Configuration for CalcomService
794
+ */ var CalcomServiceConfig = /*#__PURE__*/ function() {
795
+ function CalcomServiceConfig() {
796
+ _class_call_check$5(this, CalcomServiceConfig);
797
+ _define_property$5(this, "calcom", void 0);
798
+ _define_property$5(this, "factoryConfig", void 0);
799
+ }
800
+ _create_class$4(CalcomServiceConfig, null, [
801
+ {
802
+ key: "assertValidConfig",
803
+ value: function assertValidConfig(_config) {
804
+ // no required env-specific config currently
805
+ }
806
+ }
807
+ ]);
808
+ return CalcomServiceConfig;
809
+ }
810
+ ();
811
+
812
+ function _class_call_check$4(instance, Constructor) {
813
+ if (!(instance instanceof Constructor)) {
814
+ throw new TypeError("Cannot call a class as a function");
815
+ }
816
+ }
817
+ function _defineProperties$3(target, props) {
818
+ for(var i = 0; i < props.length; i++){
819
+ var descriptor = props[i];
820
+ descriptor.enumerable = descriptor.enumerable || false;
821
+ descriptor.configurable = true;
822
+ if ("value" in descriptor) descriptor.writable = true;
823
+ Object.defineProperty(target, descriptor.key, descriptor);
824
+ }
825
+ }
826
+ function _create_class$3(Constructor, protoProps, staticProps) {
827
+ if (protoProps) _defineProperties$3(Constructor.prototype, protoProps);
828
+ return Constructor;
829
+ }
830
+ function _define_property$4(obj, key, value) {
831
+ if (key in obj) {
832
+ Object.defineProperty(obj, key, {
833
+ value: value,
834
+ enumerable: true,
835
+ configurable: true,
836
+ writable: true
837
+ });
838
+ } else {
839
+ obj[key] = value;
840
+ }
841
+ return obj;
842
+ }
843
+ function _object_spread$1(target) {
844
+ for(var i = 1; i < arguments.length; i++){
845
+ var source = arguments[i] != null ? arguments[i] : {};
846
+ var ownKeys = Object.keys(source);
847
+ if (typeof Object.getOwnPropertySymbols === "function") {
848
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
849
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
850
+ }));
851
+ }
852
+ ownKeys.forEach(function(key) {
853
+ _define_property$4(target, key, source[key]);
854
+ });
855
+ }
856
+ return target;
857
+ }
858
+ function ownKeys$1(object, enumerableOnly) {
859
+ var keys = Object.keys(object);
860
+ if (Object.getOwnPropertySymbols) {
861
+ var symbols = Object.getOwnPropertySymbols(object);
862
+ keys.push.apply(keys, symbols);
863
+ }
864
+ return keys;
865
+ }
866
+ function _object_spread_props$1(target, source) {
867
+ source = source != null ? source : {};
868
+ if (Object.getOwnPropertyDescriptors) {
869
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
870
+ } else {
871
+ ownKeys$1(Object(source)).forEach(function(key) {
872
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
873
+ });
874
+ }
875
+ return target;
876
+ }
877
+ /**
878
+ * Injectable NestJS service that provides access to the Cal.com API.
879
+ *
880
+ * Use {@link serverContextInstance} to access API functions via the server context,
881
+ * or {@link makeUserContextInstance} to create per-mentor API instances.
882
+ *
883
+ * @example
884
+ * ```ts
885
+ * // Server context (API key or server OAuth)
886
+ * const instance = calcomApi.serverContextInstance;
887
+ * const me = await instance.getMe();
888
+ *
889
+ * // Per-mentor context
890
+ * const mentorInstance = calcomApi.makeUserContextInstance({ refreshToken: mentor.calcomRefreshToken });
891
+ * const eventTypes = await mentorInstance.getEventTypes();
892
+ *
893
+ * // Public slot query (no auth)
894
+ * const slots = await calcomApi.getAvailableSlots({ start: '...', end: '...', eventTypeId: 123 });
895
+ * ```
896
+ */ var CalcomApi = /*#__PURE__*/ function() {
897
+ function CalcomApi(config, calcomOAuthApi) {
898
+ var _this = this;
899
+ _class_call_check$4(this, CalcomApi);
900
+ _define_property$4(this, "config", void 0);
901
+ _define_property$4(this, "calcomOAuthApi", void 0);
902
+ _define_property$4(this, "calcom", void 0);
903
+ _define_property$4(this, "_serverInstance", cachedGetter(function() {
904
+ return new CalcomApiContextInstance(_this, _this.calcomServerContext);
905
+ }));
906
+ _define_property$4(this, "_publicContext", cachedGetter(function() {
907
+ return _this.calcom.calcomServerContext.makePublicContext();
908
+ }));
909
+ this.config = config;
910
+ this.calcomOAuthApi = calcomOAuthApi;
911
+ this.calcom = calcomFactory(_object_spread_props$1(_object_spread$1({}, config.factoryConfig), {
912
+ oauthContext: calcomOAuthApi.oauthContext
913
+ }))(config.calcom);
914
+ }
915
+ _create_class$3(CalcomApi, [
916
+ {
917
+ key: "calcomServerContext",
918
+ get: function get() {
919
+ return this.calcom.calcomServerContext;
920
+ }
921
+ },
922
+ {
923
+ key: "serverContextInstance",
924
+ get: /**
925
+ * Returns the cached {@link CalcomApiContextInstance} for the server context.
926
+ * All API functions are available through this instance.
927
+ */ function get() {
928
+ return this._serverInstance();
929
+ }
930
+ },
931
+ {
932
+ key: "getAvailableSlots",
933
+ get: // MARK: Public Context
934
+ /** Configured pass-through for {@link getAvailableSlots} using the public (unauthenticated) context. */ function get() {
935
+ return getAvailableSlots(this._publicContext());
936
+ }
937
+ },
938
+ {
939
+ // MARK: Context Creation
940
+ /**
941
+ * Creates a {@link CalcomApiContextInstance} for a specific user using their OAuth refresh token.
942
+ * The returned instance has all API functions scoped to that user's account.
943
+ *
944
+ * When no explicit `accessTokenCache` is provided, a per-user cache is automatically
945
+ * resolved from the cache service using an md5 hash of the refresh token as the key.
946
+ * This ensures tokens persist across requests and server restarts without collisions.
947
+ *
948
+ * @example
949
+ * ```ts
950
+ * // Automatic per-user caching (recommended):
951
+ * const userInstance = calcomApi.makeUserContextInstance({
952
+ * refreshToken: user.calcomRefreshToken
953
+ * });
954
+ *
955
+ * // With explicit cache override:
956
+ * const userInstance = calcomApi.makeUserContextInstance({
957
+ * refreshToken: user.calcomRefreshToken,
958
+ * accessTokenCache: customCache
959
+ * });
960
+ * ```
961
+ */ key: "makeUserContextInstance",
962
+ value: function makeUserContextInstance(input) {
963
+ var contextInput = _object_spread$1({}, input);
964
+ // Auto-resolve per-user cache from the refresh token if no explicit cache was given
965
+ if (!contextInput.accessTokenCache && contextInput.refreshToken) {
966
+ var userCache = this.calcomOAuthApi.cacheForRefreshToken(contextInput.refreshToken);
967
+ if (userCache) {
968
+ contextInput.accessTokenCache = userCache;
969
+ }
970
+ }
971
+ var userContext = this.calcom.calcomServerContext.makeUserContext(contextInput);
972
+ return this.makeContextInstance(userContext);
973
+ }
974
+ },
975
+ {
976
+ /**
977
+ * Creates a {@link CalcomApiContextInstance} from any {@link CalcomContext}.
978
+ */ key: "makeContextInstance",
979
+ value: function makeContextInstance(context) {
980
+ return new CalcomApiContextInstance(this, context);
981
+ }
982
+ },
983
+ {
984
+ /**
985
+ * Creates a raw {@link CalcomUserContext} from a refresh token, without wrapping in a {@link CalcomApiContextInstance}.
986
+ * Prefer {@link makeUserContextInstance} unless you need direct context access.
987
+ */ key: "makeUserContext",
988
+ value: function makeUserContext(input) {
989
+ return this.calcom.calcomServerContext.makeUserContext(input);
990
+ }
991
+ }
992
+ ]);
993
+ return CalcomApi;
994
+ }();
995
+ CalcomApi = __decorate([
996
+ Injectable(),
997
+ __param(0, Inject(CalcomServiceConfig)),
998
+ __param(1, Inject(CalcomOAuthApi))
999
+ ], CalcomApi);
1000
+ /**
1001
+ * Wraps a {@link CalcomContext} (server or user) and exposes all authenticated Cal.com API
1002
+ * functions bound to that context. Each getter delegates to the corresponding function
1003
+ * from `@dereekb/calcom`.
1004
+ *
1005
+ * Access the parent {@link CalcomApi} via {@link calcomApi} for public endpoints
1006
+ * (e.g., `calcomApi.getAvailableSlots`) or to create additional context instances.
1007
+ *
1008
+ * @example
1009
+ * ```ts
1010
+ * const instance = calcomApi.serverContextInstance;
1011
+ *
1012
+ * // Authenticated API calls
1013
+ * const me = await instance.getMe();
1014
+ * const schedules = await instance.getSchedules();
1015
+ *
1016
+ * // Access public endpoints via parent
1017
+ * const slots = await instance.calcomApi.getAvailableSlots({ start: '...', end: '...', eventTypeId: 123 });
1018
+ * ```
1019
+ */ var CalcomApiContextInstance = /*#__PURE__*/ function() {
1020
+ function CalcomApiContextInstance(calcomApi, context) {
1021
+ _class_call_check$4(this, CalcomApiContextInstance);
1022
+ _define_property$4(this, "calcomApi", void 0);
1023
+ _define_property$4(this, "context", void 0);
1024
+ this.calcomApi = calcomApi;
1025
+ this.context = context;
1026
+ }
1027
+ _create_class$3(CalcomApiContextInstance, [
1028
+ {
1029
+ key: "getMe",
1030
+ get: // MARK: User
1031
+ /**
1032
+ * Configured pass-through for {@link getMe}.
1033
+ */ function get() {
1034
+ return getMe(this.context);
1035
+ }
1036
+ },
1037
+ {
1038
+ key: "getSchedules",
1039
+ get: // MARK: Schedules
1040
+ /**
1041
+ * Configured pass-through for {@link getSchedules}.
1042
+ */ function get() {
1043
+ return getSchedules(this.context);
1044
+ }
1045
+ },
1046
+ {
1047
+ key: "createBooking",
1048
+ get: // MARK: Bookings
1049
+ /**
1050
+ * Configured pass-through for {@link createBooking}.
1051
+ */ function get() {
1052
+ return createBooking(this.context);
1053
+ }
1054
+ },
1055
+ {
1056
+ key: "getBooking",
1057
+ get: /**
1058
+ * Configured pass-through for {@link getBooking}.
1059
+ */ function get() {
1060
+ return getBooking(this.context);
1061
+ }
1062
+ },
1063
+ {
1064
+ key: "cancelBooking",
1065
+ get: /**
1066
+ * Configured pass-through for {@link cancelBooking}.
1067
+ */ function get() {
1068
+ return cancelBooking(this.context);
1069
+ }
1070
+ },
1071
+ {
1072
+ key: "getEventTypes",
1073
+ get: // MARK: Event Types
1074
+ /**
1075
+ * Configured pass-through for {@link getEventTypes}.
1076
+ */ function get() {
1077
+ return getEventTypes(this.context);
1078
+ }
1079
+ },
1080
+ {
1081
+ key: "createEventType",
1082
+ get: /**
1083
+ * Configured pass-through for {@link createEventType}.
1084
+ */ function get() {
1085
+ return createEventType(this.context);
1086
+ }
1087
+ },
1088
+ {
1089
+ key: "updateEventType",
1090
+ get: /**
1091
+ * Configured pass-through for {@link updateEventType}.
1092
+ */ function get() {
1093
+ return updateEventType(this.context);
1094
+ }
1095
+ },
1096
+ {
1097
+ key: "deleteEventType",
1098
+ get: /**
1099
+ * Configured pass-through for {@link deleteEventType}.
1100
+ */ function get() {
1101
+ return deleteEventType(this.context);
1102
+ }
1103
+ },
1104
+ {
1105
+ key: "getCalendars",
1106
+ get: // MARK: Calendars
1107
+ /**
1108
+ * Configured pass-through for {@link getCalendars}.
1109
+ */ function get() {
1110
+ return getCalendars(this.context);
1111
+ }
1112
+ },
1113
+ {
1114
+ key: "getBusyTimes",
1115
+ get: /**
1116
+ * Configured pass-through for {@link getBusyTimes}.
1117
+ */ function get() {
1118
+ return getBusyTimes(this.context);
1119
+ }
1120
+ },
1121
+ {
1122
+ key: "createWebhook",
1123
+ get: // MARK: Webhooks
1124
+ /**
1125
+ * Configured pass-through for {@link createWebhook}.
1126
+ */ function get() {
1127
+ return createWebhook(this.context);
1128
+ }
1129
+ },
1130
+ {
1131
+ key: "getWebhooks",
1132
+ get: /**
1133
+ * Configured pass-through for {@link getWebhooks}.
1134
+ */ function get() {
1135
+ return getWebhooks(this.context);
1136
+ }
1137
+ },
1138
+ {
1139
+ key: "getWebhook",
1140
+ get: /**
1141
+ * Configured pass-through for {@link getWebhook}.
1142
+ */ function get() {
1143
+ return getWebhook(this.context);
1144
+ }
1145
+ },
1146
+ {
1147
+ key: "updateWebhook",
1148
+ get: /**
1149
+ * Configured pass-through for {@link updateWebhook}.
1150
+ */ function get() {
1151
+ return updateWebhook(this.context);
1152
+ }
1153
+ },
1154
+ {
1155
+ key: "deleteWebhook",
1156
+ get: /**
1157
+ * Configured pass-through for {@link deleteWebhook}.
1158
+ */ function get() {
1159
+ return deleteWebhook(this.context);
1160
+ }
1161
+ }
1162
+ ]);
1163
+ return CalcomApiContextInstance;
1164
+ }
1165
+ ();
1166
+
1167
+ function _array_like_to_array$1(arr, len) {
1168
+ if (len == null || len > arr.length) len = arr.length;
1169
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1170
+ return arr2;
1171
+ }
1172
+ function _array_without_holes$1(arr) {
1173
+ if (Array.isArray(arr)) return _array_like_to_array$1(arr);
1174
+ }
1175
+ function _iterable_to_array$1(iter) {
1176
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1177
+ }
1178
+ function _non_iterable_spread$1() {
1179
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1180
+ }
1181
+ function _to_consumable_array$1(arr) {
1182
+ return _array_without_holes$1(arr) || _iterable_to_array$1(arr) || _unsupported_iterable_to_array$1(arr) || _non_iterable_spread$1();
1183
+ }
1184
+ function _unsupported_iterable_to_array$1(o, minLen) {
1185
+ if (!o) return;
1186
+ if (typeof o === "string") return _array_like_to_array$1(o, minLen);
1187
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1188
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1189
+ if (n === "Map" || n === "Set") return Array.from(n);
1190
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$1(o, minLen);
1191
+ }
1192
+ // MARK: Provider Factories
1193
+ function calcomServiceConfigFactory(_configService) {
1194
+ var config = {
1195
+ calcom: {}
1196
+ };
1197
+ CalcomServiceConfig.assertValidConfig(config);
1198
+ return config;
1199
+ }
1200
+ /**
1201
+ * Convenience function used to generate ModuleMetadata for an app's CalcomModule.
1202
+ */ function appCalcomModuleMetadata(config) {
1203
+ var dependencyModule = config.dependencyModule, imports = config.imports, exports$1 = config.exports, providers = config.providers;
1204
+ var dependencyModuleImport = dependencyModule ? [
1205
+ dependencyModule
1206
+ ] : [];
1207
+ return {
1208
+ imports: [
1209
+ ConfigModule
1210
+ ].concat(_to_consumable_array$1(dependencyModuleImport), _to_consumable_array$1(imports !== null && imports !== void 0 ? imports : [])),
1211
+ exports: [
1212
+ CalcomApi
1213
+ ].concat(_to_consumable_array$1(exports$1 !== null && exports$1 !== void 0 ? exports$1 : [])),
1214
+ providers: [
1215
+ {
1216
+ provide: CalcomServiceConfig,
1217
+ inject: [
1218
+ ConfigService
1219
+ ],
1220
+ useFactory: calcomServiceConfigFactory
1221
+ },
1222
+ CalcomApi
1223
+ ].concat(_to_consumable_array$1(providers !== null && providers !== void 0 ? providers : []))
1224
+ };
1225
+ }
1226
+
1227
+ // MARK: Event Types
1228
+ var CALCOM_WEBHOOK_BOOKING_CREATED = 'BOOKING_CREATED';
1229
+ var CALCOM_WEBHOOK_BOOKING_CANCELLED = 'BOOKING_CANCELLED';
1230
+ var CALCOM_WEBHOOK_BOOKING_RESCHEDULED = 'BOOKING_RESCHEDULED';
1231
+ var CALCOM_WEBHOOK_BOOKING_CONFIRMED = 'BOOKING_CONFIRMED';
1232
+
1233
+ function _define_property$3(obj, key, value) {
1234
+ if (key in obj) {
1235
+ Object.defineProperty(obj, key, {
1236
+ value: value,
1237
+ enumerable: true,
1238
+ configurable: true,
1239
+ writable: true
1240
+ });
1241
+ } else {
1242
+ obj[key] = value;
1243
+ }
1244
+ return obj;
1245
+ }
1246
+ function _object_spread(target) {
1247
+ for(var i = 1; i < arguments.length; i++){
1248
+ var source = arguments[i] != null ? arguments[i] : {};
1249
+ var ownKeys = Object.keys(source);
1250
+ if (typeof Object.getOwnPropertySymbols === "function") {
1251
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1252
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1253
+ }));
1254
+ }
1255
+ ownKeys.forEach(function(key) {
1256
+ _define_property$3(target, key, source[key]);
1257
+ });
1258
+ }
1259
+ return target;
1260
+ }
1261
+ function ownKeys(object, enumerableOnly) {
1262
+ var keys = Object.keys(object);
1263
+ if (Object.getOwnPropertySymbols) {
1264
+ var symbols = Object.getOwnPropertySymbols(object);
1265
+ keys.push.apply(keys, symbols);
1266
+ }
1267
+ return keys;
1268
+ }
1269
+ function _object_spread_props(target, source) {
1270
+ source = source != null ? source : {};
1271
+ if (Object.getOwnPropertyDescriptors) {
1272
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1273
+ } else {
1274
+ ownKeys(Object(source)).forEach(function(key) {
1275
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1276
+ });
1277
+ }
1278
+ return target;
1279
+ }
1280
+ /**
1281
+ * Creates a CalcomWebhookEvent and treats the data as the input type.
1282
+ */ function calcomWebhookEvent(event) {
1283
+ return {
1284
+ triggerEvent: event.triggerEvent,
1285
+ createdAt: event.createdAt,
1286
+ payload: event.payload
1287
+ };
1288
+ }
1289
+ var calcomEventHandlerFactory = handlerFactory(function(x) {
1290
+ return x.triggerEvent;
1291
+ });
1292
+ var calcomEventHandlerConfigurerFactory = handlerConfigurerFactory({
1293
+ configurerForAccessor: function configurerForAccessor(accessor) {
1294
+ // eslint-disable-next-line
1295
+ var fnWithKey = handlerMappedSetFunctionFactory(accessor, calcomWebhookEvent);
1296
+ var configurer = _object_spread_props(_object_spread({}, accessor), {
1297
+ handleBookingCreated: fnWithKey(CALCOM_WEBHOOK_BOOKING_CREATED),
1298
+ handleBookingCancelled: fnWithKey(CALCOM_WEBHOOK_BOOKING_CANCELLED),
1299
+ handleBookingRescheduled: fnWithKey(CALCOM_WEBHOOK_BOOKING_RESCHEDULED),
1300
+ handleBookingConfirmed: fnWithKey(CALCOM_WEBHOOK_BOOKING_CONFIRMED)
1301
+ });
1302
+ return configurer;
1303
+ }
1304
+ });
1305
+
1306
+ function _class_call_check$3(instance, Constructor) {
1307
+ if (!(instance instanceof Constructor)) {
1308
+ throw new TypeError("Cannot call a class as a function");
1309
+ }
1310
+ }
1311
+ function _defineProperties$2(target, props) {
1312
+ for(var i = 0; i < props.length; i++){
1313
+ var descriptor = props[i];
1314
+ descriptor.enumerable = descriptor.enumerable || false;
1315
+ descriptor.configurable = true;
1316
+ if ("value" in descriptor) descriptor.writable = true;
1317
+ Object.defineProperty(target, descriptor.key, descriptor);
1318
+ }
1319
+ }
1320
+ function _create_class$2(Constructor, protoProps, staticProps) {
1321
+ if (staticProps) _defineProperties$2(Constructor, staticProps);
1322
+ return Constructor;
1323
+ }
1324
+ function _define_property$2(obj, key, value) {
1325
+ if (key in obj) {
1326
+ Object.defineProperty(obj, key, {
1327
+ value: value,
1328
+ enumerable: true,
1329
+ configurable: true,
1330
+ writable: true
1331
+ });
1332
+ } else {
1333
+ obj[key] = value;
1334
+ }
1335
+ return obj;
1336
+ }
1337
+ var CALCOM_WEBHOOK_SECRET_CONFIG_KEY = 'CALCOM_WEBHOOK_SECRET';
1338
+ /**
1339
+ * Configuration for CalcomWebhookService
1340
+ */ var CalcomWebhookServiceConfig = /*#__PURE__*/ function() {
1341
+ function CalcomWebhookServiceConfig() {
1342
+ _class_call_check$3(this, CalcomWebhookServiceConfig);
1343
+ _define_property$2(this, "webhookConfig", void 0);
1344
+ }
1345
+ _create_class$2(CalcomWebhookServiceConfig, null, [
1346
+ {
1347
+ key: "assertValidConfig",
1348
+ value: function assertValidConfig(config) {
1349
+ if (!config.webhookConfig.webhookSecret) {
1350
+ throw new Error('No Cal.com webhook secret specified.');
1351
+ }
1352
+ }
1353
+ }
1354
+ ]);
1355
+ return CalcomWebhookServiceConfig;
1356
+ }
1357
+ ();
1358
+
1359
+ /**
1360
+ * Verifies a Cal.com webhook event using HMAC-SHA256 signature.
1361
+ *
1362
+ * @param secret The webhook signing secret.
1363
+ * @returns A function that verifies a Cal.com webhook event.
1364
+ */ function calcomWebhookEventVerifier(secret) {
1365
+ return function(rawBody, headers) {
1366
+ var _headers_xcalsignature256;
1367
+ var rawBodyString = rawBody.toString('utf8');
1368
+ var signature = (_headers_xcalsignature256 = headers['x-cal-signature-256']) !== null && _headers_xcalsignature256 !== void 0 ? _headers_xcalsignature256 : '';
1369
+ var expectedSignature = createHmac('sha256', secret).update(rawBodyString).digest('hex');
1370
+ var valid = signature === expectedSignature;
1371
+ var event;
1372
+ try {
1373
+ event = JSON.parse(rawBodyString);
1374
+ } catch (e) {
1375
+ event = {
1376
+ triggerEvent: '',
1377
+ createdAt: '',
1378
+ payload: {}
1379
+ };
1380
+ }
1381
+ var result = {
1382
+ valid: valid,
1383
+ event: event
1384
+ };
1385
+ return result;
1386
+ };
1387
+ }
1388
+
1389
+ function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
1390
+ try {
1391
+ var info = gen[key](arg);
1392
+ var value = info.value;
1393
+ } catch (error) {
1394
+ reject(error);
1395
+ return;
1396
+ }
1397
+ if (info.done) {
1398
+ resolve(value);
1399
+ } else {
1400
+ Promise.resolve(value).then(_next, _throw);
1401
+ }
1402
+ }
1403
+ function _async_to_generator$1(fn) {
1404
+ return function() {
1405
+ var self = this, args = arguments;
1406
+ return new Promise(function(resolve, reject) {
1407
+ var gen = fn.apply(self, args);
1408
+ function _next(value) {
1409
+ asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
1410
+ }
1411
+ function _throw(err) {
1412
+ asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
1413
+ }
1414
+ _next(undefined);
1415
+ });
1416
+ };
1417
+ }
1418
+ function _class_call_check$2(instance, Constructor) {
1419
+ if (!(instance instanceof Constructor)) {
1420
+ throw new TypeError("Cannot call a class as a function");
1421
+ }
1422
+ }
1423
+ function _defineProperties$1(target, props) {
1424
+ for(var i = 0; i < props.length; i++){
1425
+ var descriptor = props[i];
1426
+ descriptor.enumerable = descriptor.enumerable || false;
1427
+ descriptor.configurable = true;
1428
+ if ("value" in descriptor) descriptor.writable = true;
1429
+ Object.defineProperty(target, descriptor.key, descriptor);
1430
+ }
1431
+ }
1432
+ function _create_class$1(Constructor, protoProps, staticProps) {
1433
+ if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
1434
+ return Constructor;
1435
+ }
1436
+ function _define_property$1(obj, key, value) {
1437
+ if (key in obj) {
1438
+ Object.defineProperty(obj, key, {
1439
+ value: value,
1440
+ enumerable: true,
1441
+ configurable: true,
1442
+ writable: true
1443
+ });
1444
+ } else {
1445
+ obj[key] = value;
1446
+ }
1447
+ return obj;
1448
+ }
1449
+ function _ts_generator$1(thisArg, body) {
1450
+ var f, y, t, _ = {
1451
+ label: 0,
1452
+ sent: function() {
1453
+ if (t[0] & 1) throw t[1];
1454
+ return t[1];
1455
+ },
1456
+ trys: [],
1457
+ ops: []
1458
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1459
+ return d(g, "next", {
1460
+ value: verb(0)
1461
+ }), d(g, "throw", {
1462
+ value: verb(1)
1463
+ }), d(g, "return", {
1464
+ value: verb(2)
1465
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1466
+ value: function() {
1467
+ return this;
1468
+ }
1469
+ }), g;
1470
+ function verb(n) {
1471
+ return function(v) {
1472
+ return step([
1473
+ n,
1474
+ v
1475
+ ]);
1476
+ };
1477
+ }
1478
+ function step(op) {
1479
+ if (f) throw new TypeError("Generator is already executing.");
1480
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
1481
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1482
+ if (y = 0, t) op = [
1483
+ op[0] & 2,
1484
+ t.value
1485
+ ];
1486
+ switch(op[0]){
1487
+ case 0:
1488
+ case 1:
1489
+ t = op;
1490
+ break;
1491
+ case 4:
1492
+ _.label++;
1493
+ return {
1494
+ value: op[1],
1495
+ done: false
1496
+ };
1497
+ case 5:
1498
+ _.label++;
1499
+ y = op[1];
1500
+ op = [
1501
+ 0
1502
+ ];
1503
+ continue;
1504
+ case 7:
1505
+ op = _.ops.pop();
1506
+ _.trys.pop();
1507
+ continue;
1508
+ default:
1509
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1510
+ _ = 0;
1511
+ continue;
1512
+ }
1513
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1514
+ _.label = op[1];
1515
+ break;
1516
+ }
1517
+ if (op[0] === 6 && _.label < t[1]) {
1518
+ _.label = t[1];
1519
+ t = op;
1520
+ break;
1521
+ }
1522
+ if (t && _.label < t[2]) {
1523
+ _.label = t[2];
1524
+ _.ops.push(op);
1525
+ break;
1526
+ }
1527
+ if (t[2]) _.ops.pop();
1528
+ _.trys.pop();
1529
+ continue;
1530
+ }
1531
+ op = body.call(thisArg, _);
1532
+ } catch (e) {
1533
+ op = [
1534
+ 6,
1535
+ e
1536
+ ];
1537
+ y = 0;
1538
+ } finally{
1539
+ f = t = 0;
1540
+ }
1541
+ if (op[0] & 5) throw op[1];
1542
+ return {
1543
+ value: op[0] ? op[1] : void 0,
1544
+ done: true
1545
+ };
1546
+ }
1547
+ }
1548
+ /**
1549
+ * Service that makes system changes based on Cal.com webhook events.
1550
+ */ var CalcomWebhookService = /*#__PURE__*/ function() {
1551
+ function CalcomWebhookService(config) {
1552
+ _class_call_check$2(this, CalcomWebhookService);
1553
+ _define_property$1(this, "logger", new Logger('CalcomWebhookService'));
1554
+ _define_property$1(this, "_verifier", void 0);
1555
+ _define_property$1(this, "handler", calcomEventHandlerFactory());
1556
+ _define_property$1(this, "configure", calcomEventHandlerConfigurerFactory(this.handler));
1557
+ this._verifier = calcomWebhookEventVerifier(config.webhookConfig.webhookSecret);
1558
+ }
1559
+ _create_class$1(CalcomWebhookService, [
1560
+ {
1561
+ key: "updateForWebhook",
1562
+ value: function updateForWebhook(req, rawBody) {
1563
+ return _async_to_generator$1(function() {
1564
+ var headers, _this__verifier, valid, event, handled, result;
1565
+ return _ts_generator$1(this, function(_state) {
1566
+ switch(_state.label){
1567
+ case 0:
1568
+ headers = req.headers;
1569
+ _this__verifier = this._verifier(rawBody, headers), valid = _this__verifier.valid, event = _this__verifier.event;
1570
+ handled = false;
1571
+ if (!!valid) return [
1572
+ 3,
1573
+ 1
1574
+ ];
1575
+ this.logger.warn('Received invalid calcom event: ', event);
1576
+ return [
1577
+ 3,
1578
+ 3
1579
+ ];
1580
+ case 1:
1581
+ return [
1582
+ 4,
1583
+ this.updateForCalcomEvent(event)
1584
+ ];
1585
+ case 2:
1586
+ handled = _state.sent();
1587
+ _state.label = 3;
1588
+ case 3:
1589
+ result = {
1590
+ valid: valid,
1591
+ handled: handled,
1592
+ event: event
1593
+ };
1594
+ return [
1595
+ 2,
1596
+ result
1597
+ ];
1598
+ }
1599
+ });
1600
+ }).call(this);
1601
+ }
1602
+ },
1603
+ {
1604
+ key: "updateForCalcomEvent",
1605
+ value: function updateForCalcomEvent(event) {
1606
+ return _async_to_generator$1(function() {
1607
+ var handled;
1608
+ return _ts_generator$1(this, function(_state) {
1609
+ switch(_state.label){
1610
+ case 0:
1611
+ return [
1612
+ 4,
1613
+ this.handler(event)
1614
+ ];
1615
+ case 1:
1616
+ handled = _state.sent();
1617
+ if (!handled) {
1618
+ this.logger.warn('Received unexpected/unhandled calcom event: ', event);
1619
+ }
1620
+ return [
1621
+ 2,
1622
+ handled
1623
+ ];
1624
+ }
1625
+ });
1626
+ }).call(this);
1627
+ }
1628
+ }
1629
+ ]);
1630
+ return CalcomWebhookService;
1631
+ }();
1632
+ CalcomWebhookService = __decorate([
1633
+ Injectable(),
1634
+ __param(0, Inject(CalcomWebhookServiceConfig))
1635
+ ], CalcomWebhookService);
1636
+
1637
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
1638
+ try {
1639
+ var info = gen[key](arg);
1640
+ var value = info.value;
1641
+ } catch (error) {
1642
+ reject(error);
1643
+ return;
1644
+ }
1645
+ if (info.done) {
1646
+ resolve(value);
1647
+ } else {
1648
+ Promise.resolve(value).then(_next, _throw);
1649
+ }
1650
+ }
1651
+ function _async_to_generator(fn) {
1652
+ return function() {
1653
+ var self = this, args = arguments;
1654
+ return new Promise(function(resolve, reject) {
1655
+ var gen = fn.apply(self, args);
1656
+ function _next(value) {
1657
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
1658
+ }
1659
+ function _throw(err) {
1660
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
1661
+ }
1662
+ _next(undefined);
1663
+ });
1664
+ };
1665
+ }
1666
+ function _class_call_check$1(instance, Constructor) {
1667
+ if (!(instance instanceof Constructor)) {
1668
+ throw new TypeError("Cannot call a class as a function");
1669
+ }
1670
+ }
1671
+ function _defineProperties(target, props) {
1672
+ for(var i = 0; i < props.length; i++){
1673
+ var descriptor = props[i];
1674
+ descriptor.enumerable = descriptor.enumerable || false;
1675
+ descriptor.configurable = true;
1676
+ if ("value" in descriptor) descriptor.writable = true;
1677
+ Object.defineProperty(target, descriptor.key, descriptor);
1678
+ }
1679
+ }
1680
+ function _create_class(Constructor, protoProps, staticProps) {
1681
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
1682
+ return Constructor;
1683
+ }
1684
+ function _define_property(obj, key, value) {
1685
+ if (key in obj) {
1686
+ Object.defineProperty(obj, key, {
1687
+ value: value,
1688
+ enumerable: true,
1689
+ configurable: true,
1690
+ writable: true
1691
+ });
1692
+ } else {
1693
+ obj[key] = value;
1694
+ }
1695
+ return obj;
1696
+ }
1697
+ function _ts_generator(thisArg, body) {
1698
+ var f, y, t, _ = {
1699
+ label: 0,
1700
+ sent: function() {
1701
+ if (t[0] & 1) throw t[1];
1702
+ return t[1];
1703
+ },
1704
+ trys: [],
1705
+ ops: []
1706
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1707
+ return d(g, "next", {
1708
+ value: verb(0)
1709
+ }), d(g, "throw", {
1710
+ value: verb(1)
1711
+ }), d(g, "return", {
1712
+ value: verb(2)
1713
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1714
+ value: function() {
1715
+ return this;
1716
+ }
1717
+ }), g;
1718
+ function verb(n) {
1719
+ return function(v) {
1720
+ return step([
1721
+ n,
1722
+ v
1723
+ ]);
1724
+ };
1725
+ }
1726
+ function step(op) {
1727
+ if (f) throw new TypeError("Generator is already executing.");
1728
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
1729
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1730
+ if (y = 0, t) op = [
1731
+ op[0] & 2,
1732
+ t.value
1733
+ ];
1734
+ switch(op[0]){
1735
+ case 0:
1736
+ case 1:
1737
+ t = op;
1738
+ break;
1739
+ case 4:
1740
+ _.label++;
1741
+ return {
1742
+ value: op[1],
1743
+ done: false
1744
+ };
1745
+ case 5:
1746
+ _.label++;
1747
+ y = op[1];
1748
+ op = [
1749
+ 0
1750
+ ];
1751
+ continue;
1752
+ case 7:
1753
+ op = _.ops.pop();
1754
+ _.trys.pop();
1755
+ continue;
1756
+ default:
1757
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1758
+ _ = 0;
1759
+ continue;
1760
+ }
1761
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1762
+ _.label = op[1];
1763
+ break;
1764
+ }
1765
+ if (op[0] === 6 && _.label < t[1]) {
1766
+ _.label = t[1];
1767
+ t = op;
1768
+ break;
1769
+ }
1770
+ if (t && _.label < t[2]) {
1771
+ _.label = t[2];
1772
+ _.ops.push(op);
1773
+ break;
1774
+ }
1775
+ if (t[2]) _.ops.pop();
1776
+ _.trys.pop();
1777
+ continue;
1778
+ }
1779
+ op = body.call(thisArg, _);
1780
+ } catch (e) {
1781
+ op = [
1782
+ 6,
1783
+ e
1784
+ ];
1785
+ y = 0;
1786
+ } finally{
1787
+ f = t = 0;
1788
+ }
1789
+ if (op[0] & 5) throw op[1];
1790
+ return {
1791
+ value: op[0] ? op[1] : void 0,
1792
+ done: true
1793
+ };
1794
+ }
1795
+ }
1796
+ var CalcomWebhookController = /*#__PURE__*/ function() {
1797
+ function CalcomWebhookController(calcomWebhookService) {
1798
+ _class_call_check$1(this, CalcomWebhookController);
1799
+ _define_property(this, "calcomWebhookService", void 0);
1800
+ this.calcomWebhookService = calcomWebhookService;
1801
+ }
1802
+ _create_class(CalcomWebhookController, [
1803
+ {
1804
+ key: "handleCalcomWebhook",
1805
+ value: function handleCalcomWebhook(res, req, rawBody) {
1806
+ return _async_to_generator(function() {
1807
+ var _ref, response;
1808
+ return _ts_generator(this, function(_state) {
1809
+ switch(_state.label){
1810
+ case 0:
1811
+ return [
1812
+ 4,
1813
+ this.calcomWebhookService.updateForWebhook(req, rawBody)
1814
+ ];
1815
+ case 1:
1816
+ _ref = _state.sent(), _ref.valid;
1817
+ response = res.status(200); // always return a 200 status code
1818
+ response.json({});
1819
+ return [
1820
+ 2
1821
+ ];
1822
+ }
1823
+ });
1824
+ }).call(this);
1825
+ }
1826
+ }
1827
+ ]);
1828
+ return CalcomWebhookController;
1829
+ }();
1830
+ __decorate([
1831
+ Post(),
1832
+ __param(0, Res()),
1833
+ __param(1, Req()),
1834
+ __param(2, RawBody())
1835
+ ], CalcomWebhookController.prototype, "handleCalcomWebhook", null);
1836
+ CalcomWebhookController = __decorate([
1837
+ Controller('/webhook/calcom'),
1838
+ __param(0, Inject(CalcomWebhookService))
1839
+ ], CalcomWebhookController);
1840
+
1841
+ function _array_like_to_array(arr, len) {
1842
+ if (len == null || len > arr.length) len = arr.length;
1843
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1844
+ return arr2;
1845
+ }
1846
+ function _array_without_holes(arr) {
1847
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
1848
+ }
1849
+ function _class_call_check(instance, Constructor) {
1850
+ if (!(instance instanceof Constructor)) {
1851
+ throw new TypeError("Cannot call a class as a function");
1852
+ }
1853
+ }
1854
+ function _iterable_to_array(iter) {
1855
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1856
+ }
1857
+ function _non_iterable_spread() {
1858
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1859
+ }
1860
+ function _to_consumable_array(arr) {
1861
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
1862
+ }
1863
+ function _unsupported_iterable_to_array(o, minLen) {
1864
+ if (!o) return;
1865
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
1866
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1867
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1868
+ if (n === "Map" || n === "Set") return Array.from(n);
1869
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
1870
+ }
1871
+ function calcomWebhookServiceConfigFactory(configService) {
1872
+ var config = {
1873
+ webhookConfig: {
1874
+ webhookSecret: configService.get(CALCOM_WEBHOOK_SECRET_CONFIG_KEY)
1875
+ }
1876
+ };
1877
+ CalcomWebhookServiceConfig.assertValidConfig(config);
1878
+ return config;
1879
+ }
1880
+ /**
1881
+ * Configures webhooks for the service.
1882
+ */ var CalcomWebhookModule = function CalcomWebhookModule() {
1883
+ _class_call_check(this, CalcomWebhookModule);
1884
+ };
1885
+ CalcomWebhookModule = __decorate([
1886
+ Module({
1887
+ imports: [
1888
+ ConfigModule
1889
+ ],
1890
+ controllers: [
1891
+ CalcomWebhookController
1892
+ ],
1893
+ exports: [
1894
+ CalcomWebhookService
1895
+ ],
1896
+ providers: [
1897
+ {
1898
+ provide: CalcomWebhookServiceConfig,
1899
+ inject: [
1900
+ ConfigService
1901
+ ],
1902
+ useFactory: calcomWebhookServiceConfigFactory
1903
+ },
1904
+ CalcomWebhookService
1905
+ ]
1906
+ })
1907
+ ], CalcomWebhookModule);
1908
+ /**
1909
+ * Convenience function used to generate ModuleMetadata for an app's CalcomWebhookModule.
1910
+ */ function appCalcomWebhookModuleMetadata(config) {
1911
+ var dependencyModule = config.dependencyModule, imports = config.imports, exports$1 = config.exports, providers = config.providers;
1912
+ var dependencyModuleImport = dependencyModule ? [
1913
+ dependencyModule
1914
+ ] : [];
1915
+ return {
1916
+ imports: [
1917
+ ConfigModule
1918
+ ].concat(_to_consumable_array(dependencyModuleImport), _to_consumable_array(imports !== null && imports !== void 0 ? imports : [])),
1919
+ controllers: [
1920
+ CalcomWebhookController
1921
+ ],
1922
+ exports: [
1923
+ CalcomWebhookService
1924
+ ].concat(_to_consumable_array(exports$1 !== null && exports$1 !== void 0 ? exports$1 : [])),
1925
+ providers: [
1926
+ {
1927
+ provide: CalcomWebhookServiceConfig,
1928
+ inject: [
1929
+ ConfigService
1930
+ ],
1931
+ useFactory: calcomWebhookServiceConfigFactory
1932
+ },
1933
+ CalcomWebhookService
1934
+ ].concat(_to_consumable_array(providers !== null && providers !== void 0 ? providers : []))
1935
+ };
1936
+ }
1937
+
1938
+ export { CALCOM_API_KEY_CONFIG_KEY, CALCOM_CLIENT_ID_CONFIG_KEY, CALCOM_CLIENT_SECRET_CONFIG_KEY, CALCOM_REFRESH_TOKEN_CONFIG_KEY, CALCOM_SERVER_TOKEN_FILE_KEY, CALCOM_SERVICE_NAME, CALCOM_WEBHOOK_BOOKING_CANCELLED, CALCOM_WEBHOOK_BOOKING_CONFIRMED, CALCOM_WEBHOOK_BOOKING_CREATED, CALCOM_WEBHOOK_BOOKING_RESCHEDULED, CALCOM_WEBHOOK_SECRET_CONFIG_KEY, CalcomApi, CalcomApiContextInstance, CalcomOAuthAccessTokenCacheService, CalcomOAuthApi, CalcomOAuthServiceConfig, CalcomServiceConfig, CalcomWebhookController, CalcomWebhookModule, CalcomWebhookService, CalcomWebhookServiceConfig, DEFAULT_FILE_CALCOM_ACCESS_TOKEN_CACHE_DIR, appCalcomModuleMetadata, appCalcomOAuthModuleMetadata, appCalcomWebhookModuleMetadata, calcomEventHandlerConfigurerFactory, calcomEventHandlerFactory, calcomOAuthServiceConfigFactory, calcomRefreshTokenCacheKey, calcomServiceConfigFactory, calcomWebhookEvent, calcomWebhookEventVerifier, calcomWebhookServiceConfigFactory, fileCalcomOAuthAccessTokenCacheService, logMergeCalcomOAuthAccessTokenCacheServiceErrorFunction, memoryCalcomOAuthAccessTokenCacheService, mergeCalcomOAuthAccessTokenCacheServices };