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